Python:对一个函数尝试 3 次,直到全部失败 [英] Python: Try three times a function until all failed
本文介绍了Python:对一个函数尝试 3 次,直到全部失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Python
2.7中编写,遇到如下情况.我想尝试调用一个函数三次.如果所有 3 次都引发错误,我将引发我得到的最后一个错误.如果其中任何一个调用成功,我将停止尝试并立即继续.
I am writing in Python
2.7 and encounter the following situation. I would like to try calling a function three times. If all three times raise errors, I will raise the last error I get. If any one of the calls succeed, I will quit trying and continue immediately.
这是我现在所拥有的:
output = None
error = None
for _e in range(3):
error = None
try:
print 'trial %d!' % (_e + 1)
output = trial_function()
except Exception as e:
error = e
if error is None:
break
if error is not None:
raise error
是否有更好的代码片段可以实现相同的用例?
Is there a better snippet that achieve the same use case?
推荐答案
使用装饰器
from functools import wraps
def retry(times):
def wrapper_fn(f):
@wraps(f)
def new_wrapper(*args,**kwargs):
for i in range(times):
try:
print 'try %s' % (i + 1)
return f(*args,**kwargs)
except Exception as e:
error = e
raise error
return new_wrapper
return wrapper_fn
@retry(3)
def foo():
return 1/0;
print foo()
这篇关于Python:对一个函数尝试 3 次,直到全部失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文