46重试装饰器retry
from retrying import retry r''' 安装:pip install retrying Version: 1.3.4 作用:retrying库是Python中用于实现重试机制的库,它们的目的都是在遇到错误或异常时自动重试代码块,以增加代码的健壮性和可靠性. 下面的案例抽几个常用参数说明retry装饰器,当然也可以自己编写代码实现重试。 ''' # 只要是出现异常就会重试(无限重试),这里设置了为10次 num = 1 @retry def do_something(): global num if num < 10: num += 1 print('Retry') raise Exception("Retry") # stop_max_attempt_number: 用来设定最大的尝试次数,超过该次数就会停止,并抛出最后一次的异常 @retry(stop_max_attempt_number=7) def do_run(): print('Retry') raise Exception("Retry") # wait_fixed: 设置在两次retrying之间的停留时间,这里设置为1s,无限重试 @retry(wait_fixed=1000) def do_time(): print('Retry') raise IOError("Retry") # 重试功能的简单实现,count 控制重试次数,tag控制是否重试。 def reachFun(): count = 0 tag = False while count < 10 and tag is False: print('Retry') count += 1 if count == 10: tag = True if __name__ == '__main__': # do_something() # do_run() # do_time() reachFun()
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构