cam*_*uni 5 python exception-handling stack-trace
如何从Exception对象本身获取完整的堆栈跟踪?
请考虑以下代码作为问题的简化示例:
last_exception = None
try:
raise Exception('foo failed')
except Exception as e:
last_exception = e
# this happens somewhere else, decoupled from the original raise
print_exception_stack_trace(last_exception)
Run Code Online (Sandbox Code Playgroud)
编辑:我撒谎了,抱歉。e.__traceback__ 就是你想要的。
try:
raise ValueError
except ValueError as e:
print( e.__traceback__ )
>c:/python31/pythonw -u "test.py"
<traceback object at 0x00C964B8>
>Exit code: 0
Run Code Online (Sandbox Code Playgroud)
这仅在Python 3中有效;在早期版本中你无法做到这一点。