Last active
December 15, 2017 15:22
-
-
Save coconut49/314acf3cf3b8d13ad815c68cfc6ee439 to your computer and use it in GitHub Desktop.
直接用,但不会抛异常,稳如狗
This file contains 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
from contextlib import contextmanager | |
import signal | |
@contextmanager | |
def timeout(seconds=3): | |
class TimeoutError(Exception): | |
pass | |
def handler(*args,**kwargs): | |
print("[-] Timeout!") | |
raise TimeoutError | |
signal.signal(signal.SIGALRM,handler) | |
signal.alarm(seconds) | |
print("[+] Timeout setup successful") | |
try: | |
yield | |
except TimeoutError: | |
pass | |
print("[+] func terminated") | |
def dtimeout(seconds=3): | |
def realdecorator(fn): | |
def warpped(*args,**kwargs): | |
class TimeoutError(Exception): | |
pass | |
def handler(*args, **kwargs): | |
print("[-] Timeout!") | |
raise TimeoutError | |
signal.signal(signal.SIGALRM, handler) | |
signal.alarm(seconds) | |
print("[+] Timeout setup successful") | |
try: | |
fn(*args,**kwargs) | |
except TimeoutError: | |
pass | |
print("[+] func terminated") | |
return warpped | |
return realdecorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment