Python程序超时处理
使用timeout_decorator模块进行处理,该模块提供了装饰器
[root@web1 ~]# pip install timeout_decorator
[root@web1 ~]# vim a.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import time
import timeout_decorator
@timeout_decorator.timeout(5)
def outer():
time.sleep(2)
return 2
fn = outer()
print(fn)
运行
[root@web1 ~]# python3 a.py
2
超时的时候运行
[root@web1 ~]# python3 a.py 将a.py中的时间更改为6 Traceback (most recent call last): File "a.py", line 13, in <module> fn = outer() File "/usr/local/lib/python3.6/site-packages/timeout_decorator/timeout_decorator.py", line 82, in new_function return function(*args, **kwargs) File "a.py", line 9, in outer time.sleep(6) File "/usr/local/lib/python3.6/site-packages/timeout_decorator/timeout_decorator.py", line 69, in handler _raise_exception(timeout_exception, exception_message) File "/usr/local/lib/python3.6/site-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception raise exception() timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'
posted on 2021-07-05 12:20 hopeless-dream 阅读(783) 评论(0) 编辑 收藏 举报