Python timeout example.

import signal, os, subprocess

class Alarm(Exception):

def alarm_handler(signum, frame):
    raise Alarm

# start timer, currently set to go off in 3 seconds
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(3)  # 3 seconds
    print time.strfmt("%H:%M:%S")
    # perform some tasks here, for this example I use a sleep of 20 seconds which will get interrupted.
    time.sleep(20) 		# wait 20 seconds, note this time must be larger than the value of start timer.
    signal.alarm(0)  # reset the alarm
except Alarm:
    print "Oops, taking too long!"
print time.strfmt("%H:%M:%S")
This entry was posted in Uncategorized. Bookmark the permalink.