Is there a better way to implement this:
m.yanowitz at kearfott.com
Mon Jan 22 16:48:48 CET 2007
I wrote the code below (much irrelevant code removed).
This doesn't quite work. What I wanted it to do was
a) Execute function ftimed, which takes a function and a timeout
b) This will also execute function abort() as a thread.
This function just runs for the specified
number of seconds and returns.
However, before it returns, throws an exception.
c) If test() is still running when abort() is
finished, ftimed() should catch the exception and
It is catching the exception, however it continues running the function.
Why does it continue and not return?
What am I missing, or is there a better way to
implement this (having ftimed() return when the
abort-timer time is exceeded?
import time, thread, sys
thread_finished = "MAX RUN TIME EXCEEDED!"
def abort (seconds):
start_time = time.time()
while ((time.time() - start_time) < seconds):
print "script run time exceeded max_run_time of", seconds, "seconds."
i = 0
print "HELLO", i
def ftimed (func, seconds):
thread.start_new_thread (abort, (seconds,))
ftimed (test, 30)
print "Script finished"
It presently generates the following output:
$ python ./testthread.py
script run time exceeded max_run_time of 30 seconds.
Unhandled exception in thread started by <function abort at 0x009CEF30>
Traceback (most recent call last):
File "./testthread.py", line 10, in abort
MAX RUN TIME EXCEEDED!
Thanks in advance:
More information about the Python-list