首页 > 解决方案 > 从异常对象中提取完整跟踪

问题描述

我遵循了这个答案并实施了以下内容:

def B():
    try:
        raise Exception()
    except Exception as e:
        traceback_ob = e.__traceback__

        import traceback
        traceback_str = ''.join(traceback.format_exception(etype=type(e), value=e, tb=traceback_ob))

        print(traceback_str)

def A():
    B()

A()

输出是:

Traceback (most recent call last):
  File "/path/bespoke_traceback.py", line 3, in B
    raise Exception()
Exception

我需要完整的跟踪,所以在字符串中包含 A - 我怎样才能做到这一点?

具体来说 - 我需要这个字符串,而不仅仅是打印。

标签: python

解决方案


您可以将该format_exception函数与结合format_stack以获取先前的帧:

import traceback

def B():
    try:
        raise Exception("error")
    except Exception as e:
        exception = traceback.format_exception(etype=type(e), value=e, tb=e.__traceback__)
        stack = traceback.format_stack()

        # exception already holds the last (current) frame - we just want to add the previous frames
        exception[1:1] = stack[:-1]

        traceback_str = ''.join(exception)
        print(traceback_str)

def A():
    B()

A()

会给:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    A()
  File "test.py", line 14, in A
    B()
  File "test.py", line 5, in B
    raise Exception("error")
Exception: error

推荐阅读