![](/img/trans.png)
[英]How is the python traceback able to run after an exception has been raised?
[英]How to detect if an exception has been raised from a try block in python?
例如:
class ExceptionMeta(type):
def __call__(cls, *args, **kwargs):
if exception_raised_from_try_block:
do_something
else:
do_something_else
class TimeOutError(metaclass = ExceptionMeta):
pass
try:
raise TimeOutError
except Exception as e:
pass
實際的問題是我有一個代碼塊,其中try -except塊中出現超時錯誤。 每次引發TimeOut錯誤時,我都會嘗試-除阻止並發出重試5次外,將其捕獲。 此超時錯誤具有一個對象,該對象將在引發異常的情況下收集錯誤跟蹤,以便在調試問題時提供更多上下文。 但是每次在try塊中引發異常時,調用都會轉到call函數,並且最終會收集我不想要的錯誤的跟蹤信息,因為我只是在except塊中再次嘗試
python中是否有使用檢查或其他模塊的任何方式可以告訴我從try塊引發了異常?
所以你的問題是重試代碼塊...
假設您有一些類似的代碼:
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
裝飾器:
重試是用Python編寫的Apache 2.0許可的通用重試庫,用於簡化將重試行為添加到幾乎所有內容的任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.