Skip to content

Instantly share code, notes, and snippets.

@coconut49
Last active December 15, 2017 15:22
Show Gist options
  • Save coconut49/314acf3cf3b8d13ad815c68cfc6ee439 to your computer and use it in GitHub Desktop.
Save coconut49/314acf3cf3b8d13ad815c68cfc6ee439 to your computer and use it in GitHub Desktop.
直接用,但不会抛异常,稳如狗
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