python执行函数超时处理
安装func_timeout库
pip install func_timeout
设定函数超执行时间
@func_set_timeout(60) # 设定超时时间
def run_order(order):
print(os.popen(order).read())
print('脚本运行成功')
若调用函数超时自动走异常
try:
run_order(order)
except func_timeout.exceptions.FunctionTimedOut:
print('脚本运行超时')
实例
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import func_timeout
from func_timeout import func_set_timeout
@func_set_timeout(5) # 设定函数执行时间
def task():
print('开始运行!')
time.sleep(6)
return '执行成功,未超时'
if __name__ == '__main__':
try:
print(task())
# 若调用函数超时走异常
except func_timeout.exceptions.FunctionTimedOut:
print('执行函数超时')
raise TimeoutError
else:
print('没抛异常,继续')
finally:
print('不管有没有抛异常,我都继续')
运行结果
开始运行!
Traceback (most recent call last):
File "/Volumes/utility/PycharmProjects/api-smoke/src/test.py", line 19, in <module>
print(task())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/func_timeout/dafunc.py", line 185, in <lambda>
return wraps(func)(lambda *args, **kwargs : func_timeout(defaultTimeout, func, args=args, kwargs=kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/func_timeout/dafunc.py", line 101, in func_timeout
raise FunctionTimedOut('', timeout, func, args, kwargs)
func_timeout.exceptions.FunctionTimedOut: Function task (args=()) (kwargs={}) timed out after 5.000000 seconds.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Volumes/utility/PycharmProjects/api-smoke/src/test.py", line 23, in <module>
raise TimeoutError
TimeoutError
执行函数超时
不管有没有抛异常,我都继续
Process finished with exit code 1