关于Python错误重试方法总结


Posted in Python onJanuary 03, 2021

前言

Tenacity是一个 Apache 2.0授权的通用重试库,用 Python 编写,用于简化向几乎所有内容添加重试行为的任务。它起源于一个重新尝试的分支,可惜这个分支已经不复存在了。
使用Tenacity可以用来进行测试用例的重跑,爬虫脚本的重跑,以及抢票的失败重抢等等。。。可以使用的场景也是比较多。

使用

首先安装Tenacity

pip install Tenacity

无限重试

第一个重试案例,因为一直是抛出异常错误,所以无限进行重试执行

from tenacity import retry

@retry()
def test_retry():
	print('失败重试中')
 raise Exception
 
test_retry()

关于Python错误重试方法总结

成功则停止

我们来优化成功一次后程序则终止,否则继续重试。

from tenacity import retry
import random

@retry()
def test_retry():
 if random.randint(0,10) > 1:
  print('失败重试中')
  raise Exception
 else:
  print('成功')

test_retry()

关于Python错误重试方法总结

重试次数

毕竟一直重试需要消耗很多资源,所以我们可以设置一些重试的次数,比如在失败多少次后停止重试,不管有没有成功。

from tenacity import retry,stop_after_attempt
import random

@retry(stop=stop_after_attempt(7))
def test_retry():
 # if random.randint(0,10) > 1:
  print('失败重试中')
  raise Exception
 # else:
 #  print('成功')

test_retry()

关于Python错误重试方法总结

重试时间

也可以设置执行的时间

from tenacity import retry,stop_after_attempt,stop_after_delay
import random
from time import sleep
@retry(stop=stop_after_delay(3))
def test_retry():
 # if random.randint(0,10) > 1:
  sleep(1)
  print('失败重试中')
  raise Exception
 # else:
 #  print('成功')

test_retry()

关于Python错误重试方法总结

条件组合

甚至可以使用多个组合条件进行停止,哪个条件先触发则执行哪个

from tenacity import retry,stop_after_attempt,stop_after_delay
import random
from time import sleep
@retry(stop=stop_after_delay(3) | stop_after_attempt(2))
def test_retry():
 # if random.randint(0,10) > 1:
  sleep(1)
  print('失败重试中')
  raise Exception
 # else:
 #  print('成功')

test_retry()

关于Python错误重试方法总结

重试间隔

重试之间的间隔时间太短,所以让我们在重试之间等待2秒钟

from tenacity import retry,stop_after_attempt,stop_after_delay,wait_fixed
import random
import time
@retry(wait=wait_fixed(2))
def test_retry():
 # if random.randint(0,10) > 1:
  print('失败重试中')
  print(time.ctime())
  raise Exception
 # else:
 #  print('成功')

test_retry()

关于Python错误重试方法总结

重试随机间隔

我们还可以设置一些等待时间范围

from tenacity import retry,stop_after_attempt,stop_after_delay,wait_fixed,wait_random
import random
import time
@retry(wait=wait_random(min=1,max=2))
def test_retry():
 # if random.randint(0,10) > 1:
  print('失败重试中')
  print(time.ctime())
  raise Exception
 # else:
 #  print('成功')

test_retry()

关于Python错误重试方法总结

重试前日志

在执行之前打印日志

from tenacity import retry,stop_after_attempt,before_log
import logging
import sys

logging.basicConfig(stream=sys.stderr,level=logging.DEBUG)
logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3),before=before_log(logger,logging.DEBUG))
def test_retry():
 print('失败重试中')
 raise Exception('Fail')

test_retry()

关于Python错误重试方法总结

重试后日志

那么相同的,可以在执行失败后打印日志

from tenacity import retry,stop_after_attempt,after_log
import logging
import sys

logging.basicConfig(stream=sys.stderr,level=logging.DEBUG)
logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3),after=after_log(logger,logging.DEBUG))
def test_retry():
 print('失败重试中')
 raise Exception('Fail')

test_retry()

关于Python错误重试方法总结

基本常用的功能就这些了,如果有需要深入了解的可以访问github地址:https://github.com/jd/tenacity

到此这篇关于关于Python错误重试方法总结的文章就介绍到这了,更多相关Python错误重试方法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python使用xmlrpc实例讲解
Dec 17 Python
Python实现的百度站长自动URL提交小工具
Jun 27 Python
Python压缩和解压缩zip文件
Feb 14 Python
Python下使用Psyco模块优化运行速度
Apr 05 Python
Python fileinput模块使用实例
May 28 Python
Python时间模块datetime、time、calendar的使用方法
Jan 13 Python
详解Python给照片换底色(蓝底换红底)
Mar 22 Python
windows系统中Python多版本与jupyter notebook使用虚拟环境的过程
May 15 Python
Python发展史及网络爬虫
Jun 19 Python
python之array赋值技巧分享
Nov 28 Python
python爬取豆瓣电影排行榜(requests)的示例代码
Feb 18 Python
Python+OpenCV实现图片中的圆形检测
Apr 07 Python
详解python中的异常和文件读写
Jan 03 #Python
python绘制雷达图实例讲解
Jan 03 #Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
Jan 01 #Python
python安装mysql的依赖包mysql-python操作
Jan 01 #Python
python UDF 实现对csv批量md5加密操作
Jan 01 #Python
安装python依赖包psycopg2来调用postgresql的操作
Jan 01 #Python
python matlab库简单用法讲解
Dec 31 #Python
You might like
CodeIgniter生成网站sitemap地图的方法
2013/11/13 PHP
ThinkPHP跳转页success及error模板实例教程
2014/07/17 PHP
Laravel使用RabbitMQ的方法示例
2019/06/18 PHP
php实现的简单多进程服务器类完整示例
2020/02/01 PHP
CL vs ForZe BO5 第三场 2.13
2021/03/10 DOTA
js左侧多级菜单动态的解决方案
2010/02/01 Javascript
JavaScript 语言基础知识点总结(思维导图)
2013/11/10 Javascript
nodejs 整合kindEditor实现图片上传
2015/02/03 NodeJs
js仿土豆网带缩略图的焦点图片切换效果实现方法
2015/02/23 Javascript
javascript判断并获取注册表中可信任站点的方法
2015/06/01 Javascript
关于安卓手机微信浏览器中使用XMLHttpRequest 2上传图片显示字节数为0的解决办法
2016/05/17 Javascript
JavaScript暂停和继续定时器的实现方法
2016/07/18 Javascript
Bootstrap选项卡动态切换效果
2016/11/28 Javascript
jquery radio 动态控制选中失效问题的解决方法
2018/02/28 jQuery
实例讲解JavaScript截取字符串
2018/11/30 Javascript
vue-cli配置全局sass、less变量的方法
2019/06/06 Javascript
JS插入排序简单理解与实现方法分析
2019/11/25 Javascript
Python实现的数据结构与算法之队列详解
2015/04/22 Python
Python文件和流(实例讲解)
2017/09/12 Python
python执行使用shell命令方法分享
2017/11/08 Python
用python制作游戏外挂
2018/01/04 Python
Python装饰器原理与简单用法实例分析
2018/04/29 Python
Python使用tkinter库实现文本显示用户输入功能示例
2018/05/30 Python
Pandas 合并多个Dataframe(merge,concat)的方法
2018/06/08 Python
python 遍历目录(包括子目录)下所有文件的实例
2018/07/11 Python
利用Python自动化操作AutoCAD的实现
2020/04/01 Python
css3动画效果小结(推荐)
2016/07/25 HTML / CSS
Book Depository欧盟:一家领先的国际图书零售商
2019/05/21 全球购物
渗透攻击的测试步骤
2014/06/07 面试题
新闻记者实习自我鉴定
2013/09/19 职场文书
服务行业个人求职的自我评价
2013/12/12 职场文书
大学生党员承诺书
2014/05/20 职场文书
讲文明懂礼貌演讲稿
2014/09/11 职场文书
Java循环队列与非循环队列的区别总结
2021/06/22 Java/Android
python实现对doc、txt、xls等文档的读写操作
2022/04/02 Python
nginx 添加http_stub_status_module模块
2022/05/25 Servers