前言
1、通常我们在自定义一个函数后,会调用这个函数来完成我们想要的功能。就拿爬虫来举例,发送请求后服务器会在指定时间内响应(通常这个时间很短),但是有可能服务器没有返回任何数据,无论是服务器已经识别爬虫不予返回数据亦或者是服务器繁忙等其他原因,此时,爬虫程序就会一直等待来自服务器的响应,这个时候就会非常浪费资源,甚至造成程序阻塞。
2、比如说python的 requests 库中有自己的时间超时机制,例如: requests.post(url, headers=headers, data=data, proxies=proxies, timeout=15) :表示获取服务器资源的最大时间不超过15s,否则将会抛出TimeOutException异常。
3、使用python第三方 func_timeout 模块中提供的 func_set_timeout 装饰器可以非常简单的设置python程序的超时时间,超时后程序抛出 func_timeout.exceptions.FunctionTimedOut 异常。此时再用 try-except 做异常处理即可。
安装模块
pip install func_timeout
导入模块
from func_timeout import func_set_timeout
实例1
代码如下:
[En]
The code is as follows:
import time
from func_timeout import func_set_timeout
@func_set_timeout(5)
def timer():
for num in range(1, 11):
time.sleep(1)
print(num)
timer()
运行结果:
[En]
Running result:
![python之为函数执行设置超时时间(允许函数执行的最大时间)[python第三方库func_timeout]](https://www.johngo689.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
当函数的最大超时设置为11s时,程序可以正常执行,直到结束:
[En]
When the maximum timeout of the function is set to 11s, the program can execute normally until the end:
import time
from func_timeout import func_set_timeout
@func_set_timeout(11)
def timer():
for num in range(1, 11):
time.sleep(1)
print(num)
timer()
运行结果如下:
[En]
The running results are as follows:
![python之为函数执行设置超时时间(允许函数执行的最大时间)[python第三方库func_timeout]](https://www.johngo689.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
实例2
添加函数执行超时以捕获异常
[En]
Add function execution timeout to catch exception
代码如下:
[En]
The code is as follows:
import time
from func_timeout import func_set_timeout
import func_timeout
@func_set_timeout(5)
def timer():
for num in range(1,11):
time.sleep(1)
print(num)
try:
timer()
except func_timeout.exceptions.FunctionTimedOut as e:
print(e)
print("Time out!!!")
运行结果:
[En]
Running result:
![python之为函数执行设置超时时间(允许函数执行的最大时间)[python第三方库func_timeout]](https://www.johngo689.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
实例3
与python函数修饰符一起使用:
[En]
Used with the python function decorator:
代码如下:
[En]
The code is as follows:
import time
from func_timeout import func_set_timeout, FunctionTimedOut
def time_out(fn):
def wrapper(*args, **kwargs):
try:
result = fn(*args, **kwargs)
return result
except FunctionTimedOut:
print('timeout')
return None
return wrapper
@time_out
@func_set_timeout(2)
def a(name):
time.sleep(3)
print(name + 'is hls')
return 'b'
if __name__ == '__main__':
c = a(name='my name')
print(c)
运行结果:
[En]
Running result:
![python之为函数执行设置超时时间(允许函数执行的最大时间)[python第三方库func_timeout]](https://www.johngo689.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
实例4
注意: func_set_timeout 装饰器装饰python类的时候对类中的方法不起作用,即不生效;但是可以将 func_set_timeout 装饰器装饰在类里面的方法中,则对python类里面指定的方法设置函数最大执行时间(超出此时间,方法会报异常)
代码1如下:
[En]
Code 1 is as follows:
from func_timeout import func_set_timeout, FunctionTimedOut
import time
@func_set_timeout(1)
class TestFunction(object):
def __init__(self):
pass
def my_test(self):
time.sleep(10)
print('程序内等待10s后输出')
try:
a = TestFunction()
a.my_test()
print('类中的函数执行无异常')
except FunctionTimedOut as e:
print('类中函数执行抛出的异常信息:', e)
执行结果:
[En]
Execution result:
![python之为函数执行设置超时时间(允许函数执行的最大时间)[python第三方库func_timeout]](https://www.johngo689.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
代码2如下:
[En]
Code 2 is as follows:
from func_timeout import func_set_timeout, FunctionTimedOut
import time
class TestFunction(object):
def __init__(self):
pass
@func_set_timeout(1)
def my_test(self):
time.sleep(10)
print('程序内等待10s后输出')
try:
a = TestFunction()
a.my_test()
print('类中的函数执行无异常')
except FunctionTimedOut as e:
print('类中函数执行抛出的异常信息:', e)
运行结果:
[En]
Running result:
Original: https://www.cnblogs.com/hls-code/p/16415264.html
Author: 习久性成
Title: python之为函数执行设置超时时间(允许函数执行的最大时间)[python第三方库func_timeout]
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6610/
转载文章受原作者版权保护。转载请注明原作者出处!