首页 > 解决方案 > 在 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 

标签: pythondecoratorretrying

解决方案


推荐阅读