ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-07 23:57:51  阅读:302  来源: 互联网

标签:python python-3-x debugging stack-trace


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

>正在处理异常时由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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有