代码:
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message='Timeout'):
def decorator(func):
def wrapper(*args, **kwargs):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator
Python 信号处理程序总是会在主 Python 主解释器的主线程中执行,即使信号是在另一个线程中接收的。
参考文档:https://docs.python.org/zh-cn/3/library/signal.html