Python异常处理模块——retrying

发布时间 2023-04-10 11:52:14作者: 耀扬

https://zhuanlan.zhihu.com/p/420964250

安装

pip install retrying

使用

retrying 提供一个装饰器函数 retry,被装饰的函数会在运行失败的情况下重新执行,默认一直报错就一直重试。

import random
from retrying import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        print("just have a test")
        raise IOError("raise exception!")
    else:
        return "good job!"

print(do_something_unreliable())

运行这个程序,大家可以看到每次打印“just have a test”这句话的次数都不一样。这是由于我们程序中只要随机整数大于1就会打印并且抛出异常。但是由于我们有装饰器函数 retry,所以在发生异常就会重新再次执行方法,直到随机整数大于1,就会打印“good job!”。

最大重试次数

@retry(stop_max_attempt_number=5)
def do_something_limited():
    print("do something several times")
    raise Exception("raise exception")

do_something_limited()

限制最长重试时间(从执行方法开始计算)

@retry(stop_max_delay=5000)
def do_something_in_time():
    print("do something in time")
    raise Exception("raise exception")

do_something_in_time()

设置固定重试时间

@retry(wait_fixed=2000)
def wait_fixed_time():
    print("wait")
    raise Exception("raise exception")

wait_fixed_time()

设置重试时间的随机范围

@retry(wait_random_min=1000,wait_random_max=2000)
def wait_random_time():
    print("wait")
    raise Exception("raise exception")

wait_random_time()

根据异常重试

def retry_if_io_error(exception):
    return isinstance(exception, IOError)

设置特定异常类型重试

@retry(retry_on_exception=retry_if_io_error)
def retry_special_error():
    print("retry io error")
    raise IOError("raise exception")

retry_special_error()

我们自己定义一个函数,判断异常类型,然后将函数作为参数传给装饰函数 retry ,如果异常类型符合,就会进行重试。

通过返回值判断是否重试

def retry_if_result_none(result):
    """Return True if we should retry (in this case when result is None), False otherwise"""
    # return result is None
    if result =="111":
        return True


@retry(retry_on_result=retry_if_result_none)
def might_return_none():
    print("Retry forever ignoring Exceptions with no wait if return value is None")
    return "111"

might_return_none()

这里我们定义了一个判断返回值的函数,然后将这个函数作为参数传给 retry 装饰函数。当结果返回是“111”时,就会一直重试执行 might_return_none 函数。