from retrying import retry
r'''
安装:pip install retrying
Version: 1.3.4
作用:retrying库是Python中用于实现重试机制的库,它们的目的都是在遇到错误或异常时自动重试代码块,以增加代码的健壮性和可靠性.
下面的案例抽几个常用参数说明retry装饰器,当然也可以自己编写代码实现重试。
'''
# 只要是出现异常就会重试(无限重试),这里设置了为10次
num = 1
@retry
def do_something():
global num
if num < 10:
num += 1
print('Retry')
raise Exception("Retry")
# stop_max_attempt_number: 用来设定最大的尝试次数,超过该次数就会停止,并抛出最后一次的异常
@retry(stop_max_attempt_number=7)
def do_run():
print('Retry')
raise Exception("Retry")
# wait_fixed: 设置在两次retrying之间的停留时间,这里设置为1s,无限重试
@retry(wait_fixed=1000)
def do_time():
print('Retry')
raise IOError("Retry")
# 重试功能的简单实现,count 控制重试次数,tag控制是否重试。
def reachFun():
count = 0
tag = False
while count < 10 and tag is False:
print('Retry')
count += 1
if count == 10:
tag = True
if __name__ == '__main__':
# do_something()
# do_run()
# do_time()
reachFun()