[英]Python print last traceback only?
Consider the following code and traceback: 考虑以下代码和回溯:
>>> 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
>>>
I'd like to print only the most recent traceback (the one in which Exception
was raised). 我只想打印最新的回溯(引发
Exception
回溯)。
How can this be achieved? 如何做到这一点?
From the above example, I'd like to print the following, as if raise Exception
had been called outside the except
clause. 从上面的示例中,我想打印以下内容,就好像在
except
子句之外调用了raise Exception
。
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Exception
The perfect question for me. 对我来说是完美的问题。
You can suppress the exception context, that is the first part of the traceback, by explicitly raising the exception from None
: 您可以通过显式
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
This was formalized in PEP 409 and further improved in PEP 415 . 这已在PEP 409中正式确定,并在PEP 415中得到进一步改进。 The original bug request for this was filed by myself btw.
原始的错误请求由我本人提出。
Note that suppressing the context will not actually remove the context from the new exception. 请注意,抑制上下文实际上不会从新异常中删除上下文。 So you can still access the original exception:
因此,您仍然可以访问原始异常:
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.