Created
June 9, 2012 22:16
-
-
Save vadimg/2902788 to your computer and use it in GitHub Desktop.
python 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 threading | |
import functools | |
import logging | |
def timeout(duration, default=None): | |
def decorator(func): | |
class InterruptableThread(threading.Thread): | |
def __init__(self, args, kwargs): | |
threading.Thread.__init__(self) | |
self.args = args | |
self.kwargs = kwargs | |
self.result = default | |
self.daemon = True | |
def run(self): | |
try: | |
self.result = func(*self.args, **self.kwargs) | |
except Exception: | |
pass | |
@functools.wraps(func) | |
def wrap(*args, **kwargs): | |
it = InterruptableThread(args, kwargs) | |
it.start() | |
it.join(duration) | |
if it.isAlive(): | |
logging.warning('timeout in function {0}: args: {1}, kwargs: {2}'.format(func, args, kwargs)) | |
return it.result | |
return wrap | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this does not work really - threads can not be interrupted.
The thread continues to run in the Background, wasting Memory and CPU, blocking probably other devices (Network, etc ...)
You need to use a process for that, check out : https://github.com/bitranox/wrapt_timeout_decorator
Yours sincerely
Robert