30

在以下情况下,我如何获得完整的回溯,包括func2func函数的调用?

import traceback

def func():
    try:
        raise Exception('Dummy')
    except:
        traceback.print_exc()

def func2():
    func()


func2()

当我运行它时,我得到:

Traceback (most recent call last):
  File "test.py", line 5, in func
    raise Exception('Dummy')
Exception: Dummy

traceback.format_stack()不是我想要的,因为需要traceback将对象传递给第三方模块。

我对这个案例特别感兴趣:

import logging


def func():
    try:
        raise Exception('Dummy')
    except:
        logging.exception("Something awful happened!")


def func2():
    func()


func2()

在这种情况下,我得到:

ERROR:root:Something awful happened!
Traceback (most recent call last):
  File "test.py", line 9, in func
    raise Exception('Dummy')
Exception: Dummy
4

5 回答 5

38

try正如 mechmind 所回答的,堆栈跟踪仅包含引发异常的站点和块的站点之间的帧。如果您需要完整的堆栈跟踪,显然您不走运。

除了显然可以将堆栈条目从顶层提取到当前帧之外——<code>traceback.extract_stack 可以很好地管理它。问题是通过traceback.extract_stack直接检查栈帧得到的信息没有在任何时候创建回溯对象,并且loggingAPI需要回溯对象来影响回溯输出。

幸运的是,logging它不需要一个实际的回溯对象,它需要一个可以传递给traceback模块格式化例程的对象。traceback也不关心——它只使用回溯的两个属性,帧和行号。因此,应该可以创建一个鸭子类型的虚假回溯对象的链表并将其作为回溯传递。

import sys

class FauxTb(object):
    def __init__(self, tb_frame, tb_lineno, tb_next):
        self.tb_frame = tb_frame
        self.tb_lineno = tb_lineno
        self.tb_next = tb_next

def current_stack(skip=0):
    try: 1/0
    except ZeroDivisionError:
        f = sys.exc_info()[2].tb_frame
    for i in xrange(skip + 2):
        f = f.f_back
    lst = []
    while f is not None:
        lst.append((f, f.f_lineno))
        f = f.f_back
    return lst

def extend_traceback(tb, stack):
    """Extend traceback with stack info."""
    head = tb
    for tb_frame, tb_lineno in stack:
        head = FauxTb(tb_frame, tb_lineno, head)
    return head

def full_exc_info():
    """Like sys.exc_info, but includes the full traceback."""
    t, v, tb = sys.exc_info()
    full_tb = extend_traceback(tb, current_stack(1))
    return t, v, full_tb

有了这些功能,您的代码只需要进行微不足道的修改:

import logging

def func():
    try:
        raise Exception('Dummy')
    except:
        logging.error("Something awful happened!", exc_info=full_exc_info())

def func2():
    func()

func2()

...给出预期的输出:

ERROR:root:Something awful happened!
Traceback (most recent call last):
  File "a.py", line 52, in <module>
    func2()
  File "a.py", line 49, in func2
    func()
  File "a.py", line 43, in func
    raise Exception('Dummy')
Exception: Dummy

请注意,虚假回溯对象完全可用于自省——显示局部变量或作为参数——pdb.post_mortem()因为它们包含对真实堆栈帧的引用。

于 2012-11-03T15:22:53.723 回答
3

当异常冒出时收集堆栈跟踪。因此,您应该在所需堆栈的顶部打印回溯:

import traceback

def func():
    raise Exception('Dummy')

def func2():
    func()


try:
    func2()
except:
    traceback.print_exc()
于 2012-11-03T15:24:30.273 回答
3

这是基于 user4815162342 的回答,但更简约一点:

import sys
import collections

FauxTb = collections.namedtuple("FauxTb", ["tb_frame", "tb_lineno", "tb_next"])

def full_exc_info():
    """Like sys.exc_info, but includes the full traceback."""
    t, v, tb = sys.exc_info()
    f = sys._getframe(2)
    while f is not None:
        tb = FauxTb(f, f.f_lineno, tb)
        f = f.f_back
    return t, v, tb

它避免抛出虚拟异常,代价是需要使用sys._getframe(). 它假定在except​​捕获异常的子句中使用,因为它上升了两个堆栈帧(full_exc_info以及调用的函数full_exc_info——这将是调用引发代码的函数,因此已经包含在原始回溯中)。

这给出了与 user4815162342 答案中的代码相同的输出。

如果您不介意格式的细微差别,您也可以使用

import logging

def func():
    try:
        raise Exception('Dummy')
    except:
        logging.exception("Something awful happened!", stack_info=True)

def func2():
    func()

func2()

这导致

ERROR:root:Something awful happened!
Traceback (most recent call last):
  File "test.py", line 5, in func
    raise Exception('Dummy')
Exception: Dummy
Stack (most recent call last):
  File "test.py", line 12, in <module>
    func2()
  File "test.py", line 10, in func2
    func()
  File "test.py", line 7, in func
    logging.exception("Something awful happened!", stack_info=True)

在这种情况下,您将获得从尝试到异常的跟踪,以及从根调用到日志调用位置的第二次跟踪。

于 2019-09-25T20:03:17.697 回答
2

我写了一个模块,它写了一个更完整的回溯

模块在这里文档是文档

(您也可以从 pypi 获取模块

sudo pip install pd

)

要捕获和触发异常,请执行以下操作:

import pd

try:
    <python code>
except BaseException:       
    pd.print_exception_ex( follow_objects = 1 )

堆栈跟踪在这里看起来像这样:

Exception: got it

#1  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 1) at      t  test_pd.py:29
Calls next frame at:
    raise Exception('got it') at: test_pd.py:29

#2  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 2) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#3  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 3) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#4  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 4) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#5  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 5) at     test_pd.py:28
 Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#6  def kuku2(self = {'a': 42, 'b': [1, 2, 3, 4]}, depth = 6) at test_pd.py:28
Calls next frame at:
    self.kuku2( depth - 1 ) at: test_pd.py:28

#7  def main() at test_pd.py:44
Local variables:
n = {'a': 42, 'b': [1, 2, 3, 4]}
Calls next frame at:
    pd.print_exception_ex( follow_objects = 1 ) at: test_pd.py:44

follow_objects = 0 不会打印出对象内容(使用复杂的数据结构 follow_objects 可能需要很多时间)。

于 2015-02-24T18:59:42.717 回答
-1

可以从回溯中提取更多信息,有时我更喜欢更整洁、更“合乎逻辑”的信息,而不是回溯提供的带有文件、行号和代码片段的多行 blob。最好一行应该说明所有要点。

为此,我使用以下功能:

def raising_code_info():
    code_info = ''
    try:    
        frames = inspect.trace()
        if(len(frames)):
            full_method_name = frames[0][4][0].rstrip('\n\r').strip()
            line_number      = frames[1][2]
            module_name      = frames[0][0].f_globals['__name__']
            if(module_name == '__main__'):
                module_name = os.path.basename(sys.argv[0]).replace('.py','')
            class_name = ''
            obj_name_dot_method = full_method_name.split('.', 1)
            if len(obj_name_dot_method) > 1:
                obj_name, full_method_name = obj_name_dot_method
                try:
                    class_name = frames[0][0].f_locals[obj_name].__class__.__name__
                except:
                    pass
            method_name = module_name + '.'
            if len(class_name) > 0:
                method_name += class_name + '.'
            method_name += full_method_name
            code_info = '%s, line %d' % (method_name, line_number)
    finally:
        del frames
        sys.exc_clear()
    return code_info

它给 。和行号,例如:

(示例模块名称:test.py):

(line 73:)
def function1():
    print 1/0

class AClass(object):    
    def method2(self):
        a = []
        a[3] = 1

def try_it_out():
    # try it with a function
    try:
        function1()
    except Exception, what:
        print '%s: \"%s\"' % (raising_code_info(), what)

    # try it with a method
    try:
        my_obj_name = AClass()
        my_obj_name.method2()       
    except Exception, what:
        print '%s: \"%s\"' % (raising_code_info(), what)

if __name__ == '__main__':
     try_it_out()


test.function1(), line 75: "integer division or modulo by zero"
test.AClass.method2(), line 80: "list assignment index out of range"

在某些用例中可能会稍微整洁一些。

于 2013-06-09T15:15:22.860 回答