0%

Python超时机制两种办法

问题

最近做项目有一个问题,需要使用Python自动化测试apk,需要控制自动化测试的时间,设置超时时间,超时后直接跳过不运行,以及判断超时的时候可以打印日志记录

Python超时控制的两种办法(简单不复杂)

引入eventlet

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import eventlet
import time

def test_timeout(timeout_time):
eventlet.monkey_patch()
try:
with eventlet.Timeout(timeout_time):
print('before')
time.sleep(4)
print('after')
except eventlet.timeout.Timeout:
print('function run timeout')

print('function end')


test_timeout(3)

运行结果

1
2
3
before
function run timeout
function end

引入func-timeout

先安装func-timeout

1
pip install func-timeout

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time
from func_timeout import func_set_timeout, FunctionTimedOut


@func_set_timeout(3)
def test():
print('before')
time.sleep(4)
print('after')


def test_func_timeout():
try:
test()
except FunctionTimedOut as e:
print('function timeout + msg = ', e.msg)
print('end')


test_func_timeout()

结果如下:

1
2
3
before
function timeout + msg = Function test (args=()) (kwargs={}) timed out after 3.000000 seconds.
end

其中需要在控制运行时间的函数上加上@func_set_timeout注解,并且在外层捕获异常。
该库的GitHub地址为:
https://github.com/kata198/func_timeout

总结

  • 引入eventlet可以在某个代码片段设置超时时间,而func-timeout必须在某个函数上去加注解设置超时时间
  • 两个都可以简单的解决。不涉及并发场景的运行超时问题
原创技术分享,您的支持将鼓励我继续创作。