Skip to content

Instantly share code, notes, and snippets.

@winogradoff
Last active January 25, 2023 16:48
Show Gist options
  • Save winogradoff/f8945ac287b795dac897c9e9b6471e99 to your computer and use it in GitHub Desktop.
Save winogradoff/f8945ac287b795dac897c9e9b6471e99 to your computer and use it in GitHub Desktop.
Python timeout decorator
import time
from functools import wraps
from multiprocessing.context import TimeoutError
from multiprocessing.pool import ThreadPool
def timeout(seconds):
def timeout_wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
pool = ThreadPool(processes=1)
result = pool.apply_async(func, args, kwargs)
return result.get(timeout=seconds)
except TimeoutError:
return None
return wrapped
return timeout_wrapper
@timeout(seconds=3)
def endless_hello(name):
time.sleep(5)
return "Hello {}".format(name)
@timeout(seconds=3)
def hello(name):
return "Hello {}".format(name)
if __name__ == '__main__':
print(endless_hello("Rumpelstilzchen"))
print(hello("Rumpelstilzchen"))
print(endless_hello.__name__)
print(hello.__name__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment