Created
June 26, 2018 15:49
-
-
Save fionn/f30674b2510c15b5ccdc3149f21db7d2 to your computer and use it in GitHub Desktop.
Generic timeout decorator
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
import sys | |
import functools | |
import signal | |
import logging | |
def timeout(seconds: int): | |
def decorator(function): | |
def handle_timeout(signum, frame): | |
logging.error("%s received %s after %i s", frame.f_code.co_name, | |
signal.Signals(signum).name, seconds) | |
sys.tracebacklimit = 0 | |
raise TimeoutError("Execution exceeded {} seconds".format(seconds)) | |
@functools.wraps(function) | |
def wrapper(*args, **kwargs): | |
if seconds < 1: | |
raise TimeoutError("Timeout immediately") | |
signal.signal(signal.SIGALRM, handle_timeout) | |
signal.alarm(seconds) | |
try: | |
return function(*args, **kwargs) | |
finally: | |
signal.alarm(0) | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment