我对蟒蛇很陌生。我正在尝试创建一个重试装饰器,当应用于函数时,它将继续重试,直到满足某些条件(为了简单起见,比如重试10次)。
def retry():
def wrapper(func):
for i in range(0,10):
try:
func()
break
except:
continue
return wrapper
现在,这将在任何例外情况下重新尝试。如何更改它,使其重新尝试特定的异常。例如,我想把它当作:
@retry(ValueError, AbcError)
def myfunc():
//do something
我希望myfunc
只被重试,只会抛出ValueError
或AbcError
。
发布于 2013-08-07 11:18:13
您可以将异常的tuple
提供给except ..
块以捕获:
from functools import wraps
def retry(*exceptions, **params):
if not exceptions:
exceptions = (Exception,)
tries = params.get('tries', 10)
def decorator(func):
@wraps(func)
def wrapper(*args, **kw):
for i in range(tries):
try:
return func(*args, **kw)
except exceptions:
pass
return wrapper
return decorator
所有捕获的*exceptions
参数总是会导致元组的。我还添加了一个tries
关键字,因此您也可以配置重试次数:
@retry(ValueError, TypeError, tries=20)
def foo():
pass
演示:
>>> @retry(NameError, tries=3)
... def foo():
... print 'Futzing the foo!'
... bar
...
>>> foo()
Futzing the foo!
Futzing the foo!
Futzing the foo!
发布于 2013-08-07 11:22:51
from functools import wraps
class retry(object):
def __init__(self, *exceptions):
self.exceptions = exceptions
def __call__(self, f):
@wraps(f) # required to save the original context of the wrapped function
def wrapped(*args, **kwargs):
for i in range(0,10):
try:
f(*args, **kwargs)
except self.exceptions:
continue
return wrapped
用法:
@retry(ValueError, Exception)
def f():
print('In f')
raise ValueError
>>> f()
In f
In f
In f
In f
In f
In f
In f
In f
In f
In f
发布于 2013-08-07 11:18:35
您可以检查错误类:
except Exception as e:
for et in error_types: #(or args)
if isinstance(e, et):
continue
raise e #re-raise
https://stackoverflow.com/questions/18101887
复制相似问题