python - 在 Python 中重试装饰器
问题描述
我正在尝试使用重试装饰器。它运行良好,但是当达到最大重试次数时,就会出现异常。我如何避免这种异常从这种情况下很好地返回,或者当这种情况发生时如何返回一个值?
import random
from retrying import retry
@retry( wait_fixed = 500, stop_max_delay = 2000 )
def _do_something_unreliable():
actual = random.randint(0, 10)
expected = 11
print actual
print expected
print '=' *30
if actual != expected: # retry does not succeed
raise IOError( "Broken" )
_do_something_unreliable()
结果:
3
11
==============================
7
11
==============================
2
11
==============================
5
11
==============================
Traceback (most recent call last):
File "/home/itaybz/Documents/newKlara/infra/__stam.py", line 15, in <module>
_do_something_unreliable()
File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 49, in wrapped_f
return Retrying(*dargs, **dkw).call(f, *args, **kw)
File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 212, in call
raise attempt.get()
File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 247, in get
six.reraise(self.value[0], self.value[1], self.value[2])
File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 200, in call
attempt = Attempt(fn(*args, **kwargs), attempt_number, False)
File "/home/itaybz/Documents/newKlara/infra/__stam.py", line 13, in _do_something_unreliable
raise IOError( "Broken" )
IOError: Broken
6
11
==============================
Process finished with exit code 1
解决方案
推荐阅读
- go - Hyperledger Fabic 2.2.0 处理成功响应时出错。值与架构不匹配
- opengl - 是否可以同时使用索引和法线?
- ruby-on-rails - 为什么这个 Rails 迁移会给出“没有这样的表”错误?
- javascript - 通过 JS 更改 HTML 元素不会立即更新
- javascript - HTML 按钮无响应,控制台未注册事件
- amazon-web-services - 有没有办法按标签获取 AWS 资源使用情况?
- node.js - Loopback v3 将列添加到表中->“'字段列表'中的未知列 'column_name'”
- heroku - 对 Heroku WEB_CONCURRENCY 变量和 Celery --concurrency 之间的区别感到困惑
- lambda - 如何在流 API 中正确使用 .map 和 .orElseGet 的组合?
- php - 使用颤振将图像作为blob存储在mysql数据库中