Skip to content

Instantly share code, notes, and snippets.

Created Jun 9, 2012
What would you like to do?
python timeout decorator
import threading
import functools
import logging
def timeout(duration, default=None):
def decorator(func):
class InterruptableThread(threading.Thread):
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
self.result = default
self.daemon = True
def run(self):
self.result = func(*self.args, **self.kwargs)
except Exception:
def wrap(*args, **kwargs):
it = InterruptableThread(args, kwargs)
if it.isAlive():
logging.warning('timeout in function {0}: args: {1}, kwargs: {2}'.format(func, args, kwargs))
return it.result
return wrap
return decorator
Copy link

bitranox commented May 4, 2019

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 :
Yours sincerely

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment