以下片段:
import traceback
def a():
b()
def b():
try:
c()
except:
traceback.print_exc()
def c():
assert False
a()
产生这个输出:
Traceback (most recent call last):
File "test.py", line 8, in b
c()
File "test.py", line 13, in c
assert False
AssertionError
如果我想要完整的堆栈跟踪,包括对 a 的调用,我应该使用什么?
如果重要的话,我有 Python 2.6.6
编辑:我想获得的是相同的信息,如果我离开 try except 并让异常传播到顶层。例如这个片段:
def a():
b()
def b():
c()
def c():
assert False
a()
产生这个输出:
Traceback (most recent call last):
File "test.py", line 10, in <module>
a()
File "test.py", line 2, in a
b()
File "test.py", line 5, in b
c()
File "test.py", line 8, in c
assert False
AssertionError
最佳答案
这是一个基于 this answer 的函数.当不存在异常时它也可以工作:
def full_stack():
import traceback, sys
exc = sys.exc_info()[0]
stack = traceback.extract_stack()[:-1] # last one would be full_stack()
if exc is not None: # i.e. an exception is present
del stack[-1] # remove call of full_stack, the printed exception
# will contain the caught exception caller instead
trc = 'Traceback (most recent call last):\n'
stackstr = trc + ''.join(traceback.format_list(stack))
if exc is not None:
stackstr += ' ' + traceback.format_exc().lstrip(trc)
return stackstr
print full_stack()
将完整的堆栈跟踪打印到顶部,包括例如IPython 的 interactiveshell.py
调用,因为(据我所知)无法知道谁会捕获异常。反正这可能不值得弄清楚...
如果从 except
block 中调用 print full_stack()
,full_stack
将包括堆栈跟踪到 raise
。在标准 Python 解释器中,这将与您在未捕获异常时收到的消息相同(这就是 del stack[-1]
存在的原因,您不关心 except
block ,但关于 try
block )。
关于python - 如何在 Python 中获取完整的异常堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6086976/