[Tutor] how to get the return value?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Mar 5 21:32:24 CET 2006


Hi Ingo,

I'm coming into this thread a little late, but looking at your original
program:

    http://mail.python.org/pipermail/tutor/2006-March/045505.html

you may want to adjust your schedule function a bit to capture return
values.  As far as I can tell, the code throws them away when it calls
action().


###################################################################
class time_lapse(scheduler):
    def time_lapse(self, start_time, stop_time, interval, priority,
action, argument):
        def lapse():
            action(*argument)
            i=self.enter(interval, priority, lapse, ())
            if stop_time:
                if stop_time<self.timefunc():
                    self.cancel(i)
        self.enterabs(start_time, priority, lapse, ())
###################################################################

But since the scheduler runs in a separate loop than the rest of your
program, trying to return a value between the two won't work very well.


However, there are other approaches: we can use some kind of shared
container or communication channel between the main() and the scheduler,
so that they can communicate.


One possible way they can communicate is with a shared Queue:

    http://www.python.org/doc/lib/module-Queue.html

Here is an example that may help:

######################################################################
from sched import scheduler
import time
from Queue import Queue
from threading import Thread


s = scheduler(time.time, time.sleep)
q = Queue()
PRIORITY = 1

def f(n):
    """Pushes n into the queue, and then reschedules itself with
    n+1 to run five seconds later"""
    q.put(n)
    s.enter(5, PRIORITY, f, (n+1,))

## Let's prime things up.  We'll set up the scheduler, and then have
## it run on its own daemon thread.
s.enter(5, PRIORITY, f, (0,))
t = Thread(target=s.run)
t.setDaemon(True)
t.start()

## At this point, our main thread of execution is separate from the
## scheduler thread t.
while True:
    print "Waiting for event on queue."
    print q.get()
######################################################################


Does this make sense?



More information about the Tutor mailing list