Python中实现两种指定重试逻辑的方案咨询(含示例)
Python 异常重试方案实现
针对你提出的两种重试逻辑,以下是具体的实现方案:
方案1:立即重试(最多1次重试,共2次尝试)
将需要执行的操作封装,通过循环控制重试次数,失败后立即重试,第二次仍失败则进入异常处理分支:
def fun(): a = 1 x = 5 # 封装需要重试的目标操作 def target_operation(): print(x) # 替换为实际可能抛出异常的业务代码 max_retry_times = 1 # 允许重试1次,总计尝试2次 attempt_count = 0 operation_success = False while attempt_count <= max_retry_times: try: target_operation() operation_success = True break except Exception: attempt_count += 1 if attempt_count > max_retry_times: # 重试耗尽,执行异常处理 print(f"An exception occurred {a}") # 后续业务逻辑 return x + a
方案2:延迟1分钟后重试(最多1次重试)
在重试前加入time.sleep()实现延迟,其余逻辑与方案1一致:
import time def fun(): a = 1 x = 5 def target_operation(): print(x) # 替换为实际可能抛出异常的业务代码 max_retry_times = 1 attempt_count = 0 operation_success = False while attempt_count <= max_retry_times: try: target_operation() operation_success = True break except Exception: attempt_count += 1 if attempt_count > max_retry_times: print(f"An exception occurred {a}") else: # 等待1分钟(60秒)后重试 time.sleep(60) return x + a
通用装饰器方案(复用性更强)
如果需要在多个函数中复用重试逻辑,可以封装成装饰器:
import time from functools import wraps def retry(max_retries=1, delay=0): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): attempt = 0 while attempt <= max_retries: try: return func(*args, **kwargs) except Exception: attempt += 1 if attempt > max_retries: raise # 抛出异常,由调用方处理 if delay > 0: time.sleep(delay) return wrapper return decorator # 使用示例 def fun(): a = 1 x = 5 # 立即重试1次的操作 @retry(max_retries=1) def immediate_retry_op(): print(x) # 延迟60秒重试1次的操作 @retry(max_retries=1, delay=60) def delayed_retry_op(): print(x) try: immediate_retry_op() except Exception: print(f"An exception occurred {a}") # 若使用延迟重试,替换为以下代码 # try: # delayed_retry_op() # except Exception: # print(f"An exception occurred {a}") return x + a
以上方案中,目标操作与重试逻辑分离,便于维护和修改。根据实际业务需求,可以调整重试次数、延迟时间,以及异常处理的具体逻辑。
内容的提问来源于stack exchange,提问作者user6703592
相关产品推荐
相关产品推荐

