Python print last traceback only?

前提是你 提交于 2019-11-30 11:55:42
poke

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:

>>> 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. 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!