Created
October 19, 2018 09:45
-
-
Save yzhangcs/83fc5d7a78e9badf02dc7459fcbc4c3c to your computer and use it in GitHub Desktop.
Context-manager/Decorator that prevents function execution from 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
# -*- coding: utf-8 -*- | |
import functools | |
import signal | |
class timeout(object): | |
r"""Context-manager that prevents function execution from timeout. | |
Also functions as a decorator. | |
Example:: | |
>>> @timeout(2.5) | |
... def f(n): | |
... time.sleep(n) | |
>>> f(3) | |
>>> with timeout(2.5): | |
... time.sleep(3) | |
""" | |
def __init__(self, seconds=1): | |
super(timeout, self).__init__() | |
self.seconds = seconds | |
def __enter__(self): | |
signal.signal(signal.SIGALRM, self.handler) | |
# here float is accepted, different from alarm() | |
signal.setitimer(signal.ITIMER_REAL, self.seconds) | |
def __exit__(self, type, value, traceback): | |
signal.setitimer(signal.ITIMER_REAL, 0) | |
def __call__(self, func): | |
@functools.wraps(func) | |
def decorate_timeout(*args, **kwargs): | |
with self: | |
return func(*args, **kwargs) | |
return decorate_timeout | |
def handler(self, signum, frame): | |
raise TimeoutError(f"Execution time exceeded {self.seconds:.3}s.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment