Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python- how to get the output of the function used in Timer

Tags:

python

timer

I want to run a function for 10s then do other stuff. This is my code using Timer

from threading import Timer
import time

def timeout():
    b='true'
    return b

a='false'    
t = Timer(10,timeout)
t.start()

while(a=='false'):
    print '1'
    time.sleep(1)
print '2'

I know that using Timer I can print something at the end of the timer (print b instead of return b return true after 10s). What I want to know is : can I get the value returned by timeout() inside "a" to perform my while loop correctly?

Or is there another way to do it with another function ?

like image 994
user Avatar asked Aug 07 '14 18:08

user


People also ask

What time time () returns in Python?

Pythom time method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC. Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.

What does timer () do in Python?

In Python, Timer is a subclass of Thread class. Calling the start() method, the timer starts. Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions.

How do you end a timer in Python?

Python timer functions To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time. sleep(secs).


1 Answers

The return value of the function is just dropped by Timer, as we can see in the source. A way to go around this, is to pass a mutable argument and mutate it inside the function:

def work(container):
    container[0] = True

a = [False]
t = Timer(10, work, args=(a,))
t.start()

while not a[0]:
    print "Waiting, a[0]={0}...".format(a[0])
    time.sleep(1)

print "Done, result: {0}.".format(a[0])

Or, use global, but that's not the way a gentleman goes.

like image 183
bereal Avatar answered Oct 05 '22 02:10

bereal