编程语言
首页 > 编程语言> > python – `inspect.trace()`vs`traceback`

python – `inspect.trace()`vs`traceback`

作者:互联网

我对两个对象之间的区别感到困惑:

>正在处理异常时由inspect.trace()返回的帧列表
> sys.exc_info()返回的回溯[2](或在调用sys.excepthook时传递)

这两个对象是否包含相同的信息,只是组织成不同的数据结构?如果没有,那么另一个没有?

解决方法:

从inspect.trace的文档:

inspect.trace([context])

Return a list of frame records for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised.

这表明它提供了一种很好的方法来切片和切块来自sys.exc_info()[2]的帧.

哪个,如果你看一下来源:

def trace(context=1):
    """Return a list of records for the stack below the current exception."""
    return getinnerframes(sys.exc_info()[2], context)

(与3.22.7完全相同),正如它所做的那样,但它通过getinnerframes传递它,根据文档字符串使用一些有用的信息对其进行注释:

Get a list of records for a traceback’s frame and all lower frames.

Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context.

而且,因为我很好奇这实际意味着什么:

import sys
import inspect
from pprint import pprint


def errorer():
    raise Exception('foo')

def syser():
    try:
        errorer()
    except Exception, e:
        tb = sys.exc_info()[2]
        print tb.tb_frame
        print tb.tb_lasti
        print tb.tb_lineno
        print tb.tb_next

def inspecter():
    try:
        errorer()
    except Exception, e:
        pprint(inspect.trace())

当从提示中调用时,回忆起许多字段和对象具有easy-to-find定义:

>>> syser()
<frame object at 0x1441240>
6
10
<traceback object at 0x13eb3b0>
>>> inspecter()
[(<frame object at 0x14a5590>,
  '/tmp/errors.py',
  22,
  'inspecter',
  None,
  None),
 (<frame object at 0x14a21b0>,
  '/tmp/errors.py',
  8,
  'errorer',
  None,
  None)]

(行号因为我弄乱了格式化而跳了起来)

inspect.trace()显然更好一些.

标签:python,python-3-x,debugging,stack-trace
来源: https://codeday.me/bug/20191007/1869592.html