Skip to content

Instantly share code, notes, and snippets.

@baojie
Last active August 29, 2015 14:22
Show Gist options
  • Save baojie/d927de9ede5b0cbf8473 to your computer and use it in GitHub Desktop.
Save baojie/d927de9ede5b0cbf8473 to your computer and use it in GitHub Desktop.
Timeout any function
from functools import wraps
import errno
import os
import signal
import time
# timeout any function in given seconds
# solution from http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
@timeout(5)
def long_f():
for i in range(10):
print(i)
time.sleep(1)
long_f()
@baojie
Copy link
Author

baojie commented Jun 7, 2015

expected output

0
1
2
3
4
Traceback (most recent call last):
  File "timeout.py", line 35, in <module>
    long_f()
  File "timeout.py", line 20, in wrapper
    result = func(*args, **kwargs)
  File "timeout.py", line 33, in long_f
    time.sleep(1)
  File "timeout.py", line 14, in _handle_timeout
    raise TimeoutError(error_message)
__main__.TimeoutError: Timer expired

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment