a simple and useful script that uses signal to time out any function.
EDIT: use Jim Carrolls solution below
Python, 21 lines
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!
threading.Timer. Maybe you can try that :
from threading import Timer
____raise TimeExceededError, "Timed Out"
____print 'it keeps going and going ',
________print 'and going ',
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!