[英]Python print last traceback only?
考慮以下代碼和回溯:
>>> try:
... raise KeyboardInterrupt
... except KeyboardInterrupt:
... raise Exception
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Exception
>>>
我只想打印最新的回溯(引發Exception
回溯)。
如何做到這一點?
從上面的示例中,我想打印以下內容,就好像在except
子句之外調用了raise Exception
。
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Exception
對我來說是完美的問題。
您可以通過顯式from None
引發異常來抑制異常上下文,這是回溯的第一部分:
>>> try:
raise KeyboardInterrupt
except:
raise Exception from None
Traceback (most recent call last):
File "<pyshell#4>", line 4, in <module>
raise Exception from None
Exception
這已在PEP 409中正式確定,並在PEP 415中得到進一步改進。 原始的錯誤請求由我本人提出。
請注意,抑制上下文實際上不會從新異常中刪除上下文。 因此,您仍然可以訪問原始異常:
try:
try:
raise Exception('inner')
except:
raise Exception('outer') from None
except Exception as e:
print(e.__context__) # inner
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.