Welcome, guest | Sign In | My Account | Store | Cart

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!

3 comments

Louis RIVIERE 16 years, 6 months ago  # | flag

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"

Jim Carroll 16 years, 6 months ago  # | flag

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"
Symon Polley (author) 16 years, 6 months ago  # | flag

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!

Created by Symon Polley on Tue, 16 Oct 2007 (PSF)
Python recipes (4591)
Symon Polley's recipes (3)

Required Modules

Other Information and Tasks