某些常用的库如requests
的get()
函数,具有特定的参数timeout
,设置后可以在其运行超过一定时间还没运行完成时抛出超时错误。
而如果我们想为自定义函数也添加类似的“闹钟”超时检查功能,最简单的方式是使用第三方库wrapt_timeout_decorator
中的timeout()
装饰器,通过参数传递超时时长(单位:秒)即可,下面是一个简单的例子:
from wrapt_timeout_decorator import timeout
@timeout(5) # 设置超时时长为5秒
def demo_func(seconds: float) -> float:
# 此处time在函数中导入是为了绕开jupyter中wrapt_timeout_decorator与time模块的特殊错误
# 详见https://github.com/bitranox/wrapt_timeout_decorator/issues/24
import time
time.sleep(seconds)
return seconds
# 未超时时正常运行
demo_func(3)
# 超时报错
demo_func(6)
</