函数运行错误自动重试

写了一个装饰器函数,可以在函数运行发生错误的时候自动发起重试,适合爬虫场景

# -*- coding: utf-8 -*-
from functools import wraps
from typing import Tuple
import time
import random
import sys


def retry(exception_tuple: Tuple[Exception], maxretries: int, time_interval: float):
    '''
    Args:
        exception_tuple: 由Exception类组成的元组。函数只会在发生指定的错误时重试
        maxretries: 最大重试次数
        time_interval: 重试的间隔时间
    '''
    def decorator(func):
        retry_count = 0
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = None
            nonlocal retry_count
            try:
                result = func(*args, **kwargs)
            except exception_tuple as err:
                if retry_count <= maxretries:
                    retry_count += 1
                    time.sleep(time_interval)
                    print(f'! 发生错误: {err}, 即将进行第{retry_count}次尝试')
                    result = wrapper(*args, **kwargs)
                else:
                    print(f'! {err}: 在{maxretries}次尝试后依然失败.')
                    sys.exit(0)
            except Exception as err:
                print(f'! 发生未预料的错误: {err}')
                raise err
            else:
                retry_count = 0  # 成功执行一次后清除retry的记录
            return result
        return wrapper
    return decorator

if __name__ == "__main__":
    @retry(exception_tuple=(ValueError, TypeError, IndexError),
           maxretries=5,
           time_interval=3)
    def crash_randomly():
        code = random.choices([0, 1, 2, 3], weights=[0.7, 0.1, 0.1, 0.1], k=1).pop()
        if code == 1:
            raise ValueError("Error Type 1")
        elif code == 2:
            raise TypeError("Error Type 2")
        elif code == 3:
            raise IndexError("Error Type 3")
        elif code == 0:
            print("程序幸运地度过了一劫")
    
    while True:
        crash_randomly()


  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值