gpt4 book ai didi

python - `inspect.trace()` 与 `traceback`

转载 作者:太空狗 更新时间:2023-10-29 18:31:48 26 4
gpt4 key购买 nike

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

  • 处理异常时 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] 获得的帧进行切片和切 block 。

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

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 - `inspect.trace()` 与 `traceback`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10115022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com