【问题标题】:Python print last traceback only?Python只打印最后一个回溯?
【发布时间】:2014-01-07 19:10:15
【问题描述】:

考虑以下代码和回溯:

>>> 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

【问题讨论】:

标签: python python-3.x traceback


【解决方案1】:

对我来说完美的问题。

您可以通过显式引发异常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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2019-04-15
    相关资源
    最近更新 更多