所以你的问题是重试的代码块...
假设你有这样一些代码:
import random
def do_something_unreliable(msg="we have landed"):
if random.randint(0, 10) > 1:
raise Exception("Timed out...")
else:
return "Houston, {0}.".format(msg)
您可以通过执行重试5次:
for attempt in range(1, 5):
try:
do_something_unreliable()
except Exception:
# print("timeout, trying again...")
pass
else:
break
else:
do_something_unreliable()
你可以通过这样做使其可重复使用:
def retry(fn, args=None, kwargs=None, times=5, verbose=False, exceptions=None):
if args is None:
args = []
if kwargs is None:
kwargs = {}
if exceptions is None:
exceptions = (Exception,)
for attempt in range(1, times):
try:
return fn(*args, **kwargs)
except exceptions as e:
if verbose:
print("Got exception {0}({1}), retrying...".format(
e.__class__.__name__, e))
return fn(*args, **kwargs)
然后,你可以写:
>>> retry(do_something_unreliable, verbose=True)
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
'Houston, we have landed.'
>>> retry(do_something_unreliable, ['we are lucky'], verbose=True)
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
'Houston, we are lucky.'
您还可以看看retrying
装饰:
Retrying是Apache 2.0 行货通用重试库,用Python编写的,以 简化向任何事物添加重试行为的任务。
你认为除了发生什么? –
看起来你正在试图滤除可能未捕获的异常。那是对的吗?你能否进一步解释你为什么要这样做? –
看起来好像你希望你的异常在被try块阻塞时有一个行为,如果没有被捕获到另一个行为,但它们只是一个信号 - 异常不应该有副作用。 –