如何从Python中的异常对象获取堆栈跟踪?
问题描述:
如何从Exception对象本身获取完整的堆栈跟踪?
How can I get the full stack trace from the Exception object itself?
考虑以下代码作为问题的简化示例:
Consider the following code as reduced example of the problem:
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)
答
编辑:我撒谎,对不起。 e .__ traceback __
是你想要的。
I lied, sorry. e.__traceback__
is what you want.
try:
raise ValueError
except ValueError as e:
print( e.__traceback__ )
>c:/python31/pythonw -u "test.py"
<traceback object at 0x00C964B8>
>Exit code: 0
这是仅在Python 3中有效;您不能在早期版本中执行此操作。
This is only valid in Python 3; you can't do it in earlier versions.