所以你的問題是重試的代碼塊...
假設你有這樣一些代碼:
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塊阻塞時有一個行爲,如果沒有被捕獲到另一個行爲,但它們只是一個信號 - 異常不應該有副作用。 –