参考代码
#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import time
import random
from functools import wraps
def retry_on_failure(max_retries=3, delay=1, allowed_exceptions=()):
"""
函数调用出错重试装饰器
参数:
max_retries (int): 最大重试次数,默认为3
delay (int): 每次重试之间的延迟时间(秒),默认为1
allowed_exceptions (tuple): 允许重试的异常类型,默认为空(所有异常都重试)
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
retries = 0
last_exception = None
while retries < max_retries:
try:
return func(*args, **kwargs)
except allowed_exceptions if allowed_exceptions else Exception as e:
last_exception = e
retries += 1
if retries < max_retries:
print(f"调用 {func.__name__} 失败,第 {retries} 次重试... (错误: {str(e)})")
time.sleep(delay)
print(f"函数 {func.__name__} 在 {max_retries} 次尝试后仍然失败")
raise last_exception
return wrapper
return decorator
# 示例使用
@retry_on_failure(max_retries=3, delay=1, allowed_exceptions=(ValueError, RuntimeError))
def unreliable_function(x):
"""一个可能失败的示例函数"""
if random.random() < 0.7: # 70%的概率失败
raise ValueError("随机失败: 数值错误")
return x * 2
# 测试代码
if __name__ == "__main__":
try:
result = unreliable_function(5)
print(f"调用成功,结果: {result}")
except Exception as e:
print(f"最终失败: {str(e)}") 网友回复


