ITPub博客

首页 > IT职业 > IT生活 > python函数超时怎么自动退出?

python函数超时怎么自动退出?

IT生活 作者:ldzsl 时间:2021-09-11 10:04:28 0 删除 编辑

 

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

安装timeout-decorator库:

pip3 install timeout-decorator

编写异常语句:

@timeout_decorator.timeout(5, timeout_exception=StopIteration)

函数限制超时:

@timeout_decorator.timeout(5, use_signals=False)

解决案例:

import timeout_decorator
@timeout_decorator.timeout(5)
def mytest():
    print("Start")
    for i in range(1, 10):
        time.sleep(1)
        print("{} seconds have passed".format(i))
def main():
    mytest()
if __name__ == '__main__':
main()

《相关推荐:php框架》

这是非常使用的案例技巧功能,很适合大家在项目编写时候,解决遇到的问题,大家可以参考学习,但是面对不同的场景,还是要分情况使用哦~

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2325/viewspace-2831521/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2016-01-19

  • 博文量
    72
  • 访问量
    12922