Created
December 5, 2008 16:44
-
-
Save dbr/32398 to your computer and use it in GitHub Desktop.
signal based timeout for function call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
class TimeExceededError(Exception):pass | |
def run_cmd(cmd, timeout = 0): | |
import signal | |
def alarmHandler(signum, frame): | |
raise TimeExceededError, "Took too long to execute" | |
signal.signal(signal.SIGALRM, alarmHandler) | |
signal.alarm(1) | |
cmd() | |
def myfunc(): | |
import time | |
time.sleep(2) | |
return | |
try: | |
run_cmd(myfunc) | |
except TimeExceededError: | |
print "Function timed out!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment