某些常用的库如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)
并且不只是函数,类中的静态方法亦可使用:
class Demo:
@timeout(5) # 设置超时时长为5秒
@staticmethod
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 = Demo()
demo.demo_func(3)
Demo().demo_func(6)
使用场景非常之多,例如之前就用它来解决fabric模拟执行nohup命令时的持续阻塞问题。还能在哪些时候派上用场,就需要大家去实践了。
好了,今天的分享就到这里,希望对大家有所帮助。
对于Python有兴趣想一起交流的,都可以加下微信,在这里我也准备了一份学习资料送给大家,主要包含爬虫入门(爬虫工作流程 http工作流程)、逆向工程、逆向算法、异步爬虫、安卓逆向这几个板块。(截图为部分展示)
适合Python入门的朋友学习,都是精华,快来白嫖!



