Skip to content

Instantly share code, notes, and snippets.

@Zheaoli
Last active December 24, 2020 09:08
Show Gist options
  • Save Zheaoli/6e9d7349ad737b5ed914e840a53a2aed to your computer and use it in GitHub Desktop.
Save Zheaoli/6e9d7349ad737b5ed914e840a53a2aed to your computer and use it in GitHub Desktop.
import functools
import signal
class TimeoutException(BaseException):
pass
def timeout_decorator(handler=None, timeout=None):
def decorator(func):
def __quit(signum, frame):
raise TimeoutException
@functools.wraps(func)
def wrap(*args, **kwargs):
signal.signal(signal.SIGALRM, __quit)
signal.alarm(timeout)
try:
result = func(*args, **kwargs)
return result
except TimeoutException as e:
if not handler:
raise e
handler(e)
finally:
signal.alarm(0)
return wrap
return decorator
@timeout_decorator(handler=lambda x: print(type(x)), timeout=1)
def abc():
while True:
results = 1
for i in range(10000):
results *= i
try:
abc()
except BaseException:
pass
abc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment