Python只输出最后的追溯?

Python print last traceback only?

考虑以下代码和回溯:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
Traceback (most recent call last):
  File"<stdin>", line 4, in <module>
Exception


对我来说是个完美的问题。

您可以通过显式地引发异常from None来抑制异常上下文,这是回溯的第一部分:

1
2
3
4
5
6
7
8
9
>>> 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中进一步改进。最初的错误请求是由我自己提交的。

请注意,抑制上下文实际上不会从新异常中移除上下文。所以您仍然可以访问原始异常:

1
2
3
4
5
6
7
try:
    try:
        raise Exception('inner')
    except:
        raise Exception('outer') from None
except Exception as e:
    print(e.__context__) # inner