python 重复尝试【retry】编写

  1. 自定义
def retry(times, interval):
    def decorator(f)
        def wrap(*args, **kwargs):
            while times:
                try:
                    return f(*args, **kwargs)
                except ConnectionError:
                    times -= 1
                    time.sleep(interval)
                    continue
        return wrap
    return decorator


# 重试3次每次间隔10秒
@retry(times=3, interval=10)
def f1():
    # do some connections
    return 0

# 重试5次每次间隔15秒
@retry(times=5, interval=15)
def f2():
    # do some other connections
    return 0

  1. 第三方库
from tenacity import retry, stop_after_attempt, wait_fixed

# 不带任何参数的重试
@retry
def f():
    # do some connections
    return 0

# 重试5次每次间隔15秒
@retry(stop=stop_after_attempt(5), wait=wait_fixed(15))
def f():
    # do some connections
    return 0

原文地址:https://www.cnblogs.com/amize/p/15014246.html