Last active
December 24, 2020 09:08
-
-
Save Zheaoli/6e9d7349ad737b5ed914e840a53a2aed to your computer and use it in GitHub Desktop.
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 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