def time_limit(seconds: float):
def signal_handler(signum, frame):
raise TimeoutException("Timed out!")
signal.setitimer(signal.ITIMER_REAL, seconds)
signal.signal(signal.SIGALRM, signal_handler)
try:
yield
finally:
signal.setitimer(signal.ITIMER_REAL, 0)用中文解释这段代码
这段代码发生了如题错误。
原来是windows平台并不支持signal的若干函数,例如setitimer,signal等,将代码修改为如下:
import threading
import contextlib
class TimeoutException(Exception):
pass
@contextlib.contextmanager
def time_limit(seconds: float):
# 创建一个线程计时器
timer = threading.Timer(seconds, lambda: _raise_exception())
try:
timer.start()
yield
finally:
timer.cancel()
def _raise_exception():
raise TimeoutException("Timed out!")