python的重试模块retry、retrying
一,retry模块
1,pip安装retry模块
1
|
pip install retry
|
2,retry介绍
1
2 3 4 5 6 7 8 9 10 11 |
def retry(exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff=1, jitter=0, logger=logging_logger):
"""Return a retry decorator. :param exceptions: an exception or a tuple of exceptions to catch. default: Exception. :param tries: the maximum number of attempts. default: -1 (infinite). :param delay: initial delay between attempts. default: 0. :param max_delay: the maximum value of delay. default: None (no limit). :param backoff: multiplier applied to delay between attempts. default: 1 (no backoff). :param jitter: extra seconds added to delay between attempts. default: 0. fixed if a number, random if a range tuple (min, max) :param logger: logger.warning(fmt, error, delay) will be called on failed attempts. default: retry.logging_logger. if None, logging is disabled. |
3,参数介绍
1
2 3 4 5 6 7 |
:param exceptions:捕获异常或异常元组。 默认:Exception。
:param tries:Exception最大尝试次数。 默认值:-1(无限)。 :param delay:尝试之间的初始延迟。 默认值:0。 :param max_delay:指定最大间隔时间,backoff参数触发的休眠时间大于max_delay时,休眠时间以max_delay为准则。。 默认值:无(无限制)。 :param backoff:尝试间隔时间,成倍数增加。 乘法器应用于尝试之间的延迟。 默认值:1(无退避)。 :param jitter:额外的秒数添加到尝试之间的延迟。如果数字固定,则随机如果范围元组(最小值,最大值) 默认值:0。 :param logger:logger.warning(fmt,error,delay)将在失败尝试中调用。 默认值:retry.logging_logger。 如果无,则记录被禁用。 |
4,实例
1
2 3 4 5 6 7 8 9 10 11 |
import time
from retry import retry @retry(tries=5,delay=1,backoff=1,jitter=(5,7)) def make_trouble(): '''Retry on ValueError or TypeError, sleep 1, 2, 4, 8, ... seconds between attempts.''' print (1, int(time.time())) raise ValueError if __name__ == '__main__': make_trouble() |
二,retrying模块
详解: https://blog.csdn.net/liereli/article/details/79993114
1,pip安装retrying模块
1
|
pip install retrying
|
2,retrying参数介绍
a) 源码如下:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
def __init__(self,
stop=None, wait=None, stop_max_attempt_number=None, stop_max_delay=None, wait_fixed=None, wait_random_min=None, wait_random_max=None, wait_incrementing_start=None, wait_incrementing_increment=None, wait_exponential_multiplier=None, wait_exponential_max=None, retry_on_exception=None, retry_on_result=None, wrap_exception=False, stop_func=None, wait_func=None, wait_jitter_max=None): self._stop_max_attempt_number = 5 if stop_max_attempt_number is None else stop_max_attempt_number self._stop_max_delay = 100 if stop_max_delay is None else stop_max_delay self._wait_fixed = 1000 if wait_fixed is None else wait_fixed self._wait_random_min = 0 if wait_random_min is None else wait_random_min self._wait_random_max = 1000 if wait_random_max is None else wait_random_max self._wait_incrementing_start = 0 if wait_incrementing_start is None else wait_incrementing_start self._wait_incrementing_increment = 100 if wait_incrementing_increment is None else wait_incrementing_increment self._wait_exponential_multiplier = 1 if wait_exponential_multiplier is None else wait_exponential_multiplier self._wait_exponential_max = MAX_WAIT if wait_exponential_max is None else wait_exponential_max self._wait_jitter_max = 0 if wait_jitter_max is None else wait_jitter_max |
b) 参数详解如下:
stop_max_attempt_number:在停止之前尝试的最大次数,最后一次如果还是有异常则会抛出异常,停止运行,默认为5次。
stop_max_delay:最大延迟时间,大概意思就是:如果调用的函数出现异常,那么就会重复调用这个函数,最大调用时间,默认为100毫秒。
wait_fixed:两次调用方法期间停留时长, 如果出现异常则会一直重复调用,默认 1000毫秒。
wait_random_min:在两次调用方法停留时长,停留最短时间,默认为0
wait_random_max:在两次调用方法停留时长,停留最长时间,默认为1000毫秒
wait_incrementing_increment:每调用一次则会增加的时长,默认 100毫秒
wait_exponential_multiplier和wait_exponential_max:以指数的形式产生两次retrying之间的停留时间,产生的值为2^previous_attempt_number * wait_exponential_multiplier,previous_attempt_number是前面已经retry的次数,如果产生的这个值超过了wait_exponential_max的大小,那么之后两个retrying之间的停留值都为wait_exponential_max
retry_on_exception: 指定一个函数,如果此函数返回指定异常,则会重试,如果不是指定的异常则会退出。
wrap_exception:参数设置为True/False,如果指定的异常类型,包裹在RetryError中,会看到RetryError和程序抛的Exception error
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
import time
from retrying import retry def run2(exception): # return isinstance(exception, TypeError) return isinstance(exception, ZeroDivisionError) @retry(retry_on_exception=run2,stop_max_attempt_number=5) def run(): print("开始重试") time.sleep(1) a = 1 / 0 if __name__ == '__main__': run() |
retry_on_result:指定一个函数,如果指定的函数返回True,则重试,否则抛出异常退出
from retrying import retry
1
2 3 4 5 6 7 8 9 |
def run2(r):
return r == 1 @retry(retry_on_result=run2) def run(): print("开始重试") a = 1 return a if __name__ == '__main__': run() |
stop_func: 每次抛出异常时都会执行的函数,如果和stop_max_delay、stop_max_attempt_number配合使用,则后两者会失效
指定的stop_func会有两个参数:attempts, delay
1
2 3 4 5 6 7 8 9 10 11 12 |
from retrying import retry
def stop_func(attempts, delay): print("stop_func %d--->%d" % (attempts,delay)) @retry(wait_fixed=10000,wait_exponential_multiplier=100, stop_func=stop_func) def test_stop_func(): print("test_stop_func") raise Exception test_stop_func() # stop_max_delay失去了作用,会一直循环下去 |
wait_func:和stop_func用法差不多,不多描述
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
2022-04-09 Windows10下安装MySQL8.0
2022-04-09 MySQL允许远程登录的授权方法