a simple and useful script that uses signal to time out any function.
EDIT: use Jim Carrolls solution below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import signal
def timeout(signum, frame):
raise TimeExceededError, "Timed Out"
#this is an infinite loop, never ending under normal circumstances
def main():
print 'it keeps going and going ',
while 1:
print 'and going ',
#SIGALRM is only usable on a unix platform
signal.signal(signal.SIGALRM, timeout)
#change 5 to however many seconds you need
signal.alarm(5)
try:
main()
except TimeExceededError:
print "whoops"
|
thanks for the comments!
Tags: algorithms
threading.Timer. Maybe you can try that :
from threading import Timer
def timeout():
____raise TimeExceededError, "Timed Out"
def main():
____print 'it keeps going and going ',
____while 1:
________print 'and going ',
Timer(5, timeout).start()
try:
____main()
except TimeExceededError:
____print "whoops"
Except... an exception raised in one thread isn't caught in another. I just tried that example in python 2.5, and it never printed "whoops"
To communicate across threads, I think you always need some sort of thread-safe queue or messaging system. In the past I've used wxWidgets messages without any trouble. I think the best thing you can do that's this simple is:
very nice. i like this solution as its also usable on windows platforms! you should post this solution, it would probably save alot of people alot of time!