重复Python函数调用异常?

Hai*_*ipa 10 python

嘿大家我正在研究数据抓取项目,如果引发异常,我正在寻找一种简洁的方法来重复函数调用.

伪代码:

try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times, 
        until success(no exceptions raised) otherwise raise myError2
Run Code Online (Sandbox Code Playgroud)

我意识到这根本不是最佳实践,但我正在研究一些不可靠的不同代码/网络层,我无法实际调试它们.

现在我正在通过一系列尝试来完成这个尝试\除了块,它让我的眼睛流血.

优雅的想法谁?

use*_*379 11

要做到你想要的,你可以做如下的事情:

import functools
def try_x_times(x, exceptions_to_catch, exception_to_raise, fn):
    @functools.wraps(fn) #keeps name and docstring of old function
    def new_fn(*args, **kwargs):
        for i in xrange(x):
            try:
                return fn(*args, **kwargs)
            except exceptions_to_catch:
                 pass
        raise exception_to_raise
    return new_fn
Run Code Online (Sandbox Code Playgroud)

然后你只需将旧函数包装在这个新函数中:

#instead of
#risky_method(1,2,'x')
not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
not_so_risky_method(1,2,'x')

#or just
try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')
Run Code Online (Sandbox Code Playgroud)

  • 使用functools.wraps而不是自己更改\ _ _ _ name\_ _ _. (2认同)
  • 凉.我实际上最终使用的是http://peter-hoffmann.com/2010/retry-decorator-python.html,但这几乎是一样的想法. (2认同)

Min*_*ang 8

使用循环

i = 0
while True:
  try: myfunc(x); break;
  except myError:
    i = i + 1;
    # print "Trying again"
    if i > 5: raise myError2;
Run Code Online (Sandbox Code Playgroud)