Skip to content

Instantly share code, notes, and snippets.

@notgba
Created December 1, 2015 17:20
Show Gist options
  • Select an option

  • Save notgba/c68b6baca8c4925e3762 to your computer and use it in GitHub Desktop.

Select an option

Save notgba/c68b6baca8c4925e3762 to your computer and use it in GitHub Desktop.
timeout装饰器
import signal
import functools
# 定义一个Exception,后面超时抛出
class TimeoutError(Exception):
pass
def timeout(seconds, error_message='Function call timed out'):
def decorated(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return functools.wraps(func)(wrapper)
return decorated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment