import signal
import time
from contextlib import contextmanager
@contextmanager
def timeout_after(seconds: int):
# Register a function to raise a TimeoutError on the signal.
signal.signal(signal.SIGALRM, raise_timeout)
# Schedule the signal to be sent after `seconds`.
signal.alarm(seconds)
try:
yield
finally:
# Unregister the signal, so it won't be triggered if the timeout is not reached.
signal.signal(signal.SIGALRM, signal.SIG_IGN)
def raise_timeout(_, __):
raise TimeoutError
# Used as such:
@timeout_after(3)
def hello():
time.sleep(5)
print("hello")
if __name__ == '__main__':
with timeout_after(3):
time.sleep(5)
# hello()
# time.sleep(10)
【python超时】超时处理
本文介绍如何利用Python的signal模块实现运行中的函数如果超过预设的时间限制则自动终止的功能。通过定义一个上下文管理器来设置信号处理函数,并在达到指定秒数后触发超时异常,从而优雅地终止长时间运行的任务。





