Last active
July 24, 2019 16:10
-
-
Save goddoe/c667f8eed7981e272b7374e2ed1915ff to your computer and use it in GitHub Desktop.
Timeout
This file contains 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
from functools import wraps | |
import errno | |
import os | |
import signal | |
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 | |
# ====================== | |
from timeout import timeout | |
@timeout | |
def long_running_function1(): | |
pass | |
@timeout(5) | |
def long_running_function2(): | |
pass | |
@timeout(30, os.strerror(errno.ETIMEDOUT)) | |
def long_running_function3(): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment