考虑以下代码和回溯:
>>> 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
被引发的追溯)。
如何实现这一目标?
从上面的示例中,我想打印以下内容,就像在raise Exception
子句之外调用except
一样。
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
Exception
答案 0 :(得分:31)
对我来说是个完美的问题。
您可以通过显式引发异常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进一步改进。 original bug request这是我自己提交的。
请注意,抑制上下文实际上不会从新异常中删除上下文。所以你仍然可以访问原来的例外:
try:
try:
raise Exception('inner')
except:
raise Exception('outer') from None
except Exception as e:
print(e.__context__) # inner