Last active
July 25, 2022 19:59
-
-
Save plutec/2fc31233612528f9181a to your computer and use it in GitHub Desktop.
Decorator to add timeout to a function in python
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
from functools import wraps | |
import errno | |
import os | |
import signal | |
import time | |
#Source: 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(6) | |
def long_time_function(): | |
time.sleep(4) #Works | |
@timeout(4) | |
def long_time_function2(): | |
time.sleep(5) #Doesn't work | |
if __name__ == '__main__': | |
long_time_function() | |
long_time_function2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Caveats using Signals
as ABADGER1999 points out in his blog https://anonbadger.wordpress.com/2018/12/15/python-signal-handlers-and-exceptions/
using signals and the TimeoutException is probably not the best idea - because it can be catched in the decorated function.
Of course You can use Your own Exception, derived from the Base Exception Class, but the code might still not work as expected -
see the next example - You may try it out in
jupyter <https://mybinder.org/v2/gh/bitranox/wrapt_timeout_decorator/master?filepath=jupyter_test_wrapt_timeout_decorator.ipynb>
_:You might try that decorator : https://github.com/bitranox/wrapt_timeout_decorator
.. code-block:: py