栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python异常自动重试--retrying

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python异常自动重试--retrying

通常为了防止程序出现异常而终止,我们会采用try来获取异常。
列如调用第三方API,设备状态心跳上报网络不稳定都可能发生异常。
我们希望当程序发生异常时能自动重复调用或者指定调用次数等。
python retrying库,完美的实现这个需求。
retrying 提供一个装饰器函数 retry,被装饰的函数会在运行失败的情况下重新执行,默认一直报错就一直重试。

安装库 pip install retrying

from retrying import retry
import time

1.无限重试
@retry()
def run():
    print('重复调用')
    time.sleep(1)
    raise Exception
2.最大重试次数 stop_max_attempt_number
@retry(stop_max_attempt_number=5)
def run():
    print('重复调用')
    time.sleep(1)
    raise Exception
3.最大重试时间 stop_max_delay 单位毫秒
@retry(stop_max_delay=5000)
def run():
    print('重复调用')
    time.sleep(1)
    raise Exception
4.重试间隔时间 wait_fixed 单位毫秒
@retry(wait_fixed=5000)
def run():
    print('重复调用')
    raise Exception
5.重试同时调用其他方法 stop_func
#参数 attempts, delay必填项
def log_error(attempts, delay):
    print('记录异常')

#指定异常重复调用函数
@retry(stop_func=log_error)
def run():
    print('重复调用')
    time.sleep(1)
    raise Exception
if __name__ == '__main__':
    run()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968193.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号