Python打印最后的追溯只?

kir*_*iri 13 python traceback python-3.x

请考虑以下代码和回溯:

>>> 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
>>> 
Run Code Online (Sandbox Code Playgroud)

我想只打印最近的追溯(其中一个Exception被提出).
怎么能实现这一目标?


从上面的例子中,我想打印以下内容,就像raise Exceptionexcept子句之外调用一样.

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Exception
Run Code Online (Sandbox Code Playgroud)

pok*_*oke 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
Run Code Online (Sandbox Code Playgroud)

这在PEP 409中正式确定,并在PEP 415中得到进一步改进.将原来的错误请求,这个被自己BTW申请.


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

try:
    try:
        raise Exception('inner')
    except:
        raise Exception('outer') from None
except Exception as e:
    print(e.__context__) # inner
Run Code Online (Sandbox Code Playgroud)