Last active
January 25, 2023 16:48
-
-
Save winogradoff/f8945ac287b795dac897c9e9b6471e99 to your computer and use it in GitHub Desktop.
Python timeout decorator
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
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