ActiveState Code

Recipe 534115: Function Timeout


a simple and useful script that uses signal to time out any function.

EDIT: use Jim Carrolls solution below

Python
 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"

Discussion

thanks for the comments!

Comments

  1. 1. At 8:05 a.m. on 19 oct 2007, Louis Riviere said:

    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"

  2. 2. At 11:25 a.m. on 19 oct 2007, Jim Carroll said:

    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:

    from threading import Timer
    import thread, time, sys
    
    def timeout():
        thread.interrupt_main()
    
    def main():
        print 'it keeps going and going ',
        while 1:
            print 'and going '
        time.sleep(1)
    
    try:
        Timer(5, timeout).start()
        main()
    except:
        print "whoops"
    
  3. 3. At 3:30 p.m. on 19 oct 2007, Symon Polley (the author) said:

    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!

Sign in to comment