可以使用 Python 的 signal
模块实现代码超时检测功能。代码如下:
import signal
class TimeoutError(Exception):
pass
def timeout_handler(signum, frame):
raise TimeoutError("The operation timed out.")
def set_timeout(seconds):
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(seconds)