python - 如何在 Python 中获取完整的异常堆栈跟踪

标签 python exception exception-handling traceback

以下片段:

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/

相关文章:

java - 无限期地等待可能永远不会到达的消息

python - 在 amazon s3 boto bucket 中设置特定权限

python - 在 UNIX 环境中运行时,防止在非引号 python 脚本参数中扩展通配符

java - 一个封装 java io 的库,不强制客户端使用检查异常

c# - EnterpriseLibrary 记录到数据库不起作用

Java 术语 : Why compile-time error and not compile-time exception?

python - AngularJS + Django - 主要优点和缺点

python - 有没有办法在python函数的每个return语句之前执行一条语句?

postgresql - 在没有程序代码的情况下处理 PostgresQL 中的除法错误 - 这可能吗?

python : How to continue execution inside a try statement after an exception stop it