gpt4 book ai didi

python - 堆栈和框架有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 20:35:34 25 4
gpt4 key购买 nike

在什么情况下我想使用一种而不是另一种?

有什么区别:

>>> import inspect
>>> print(inspect.getouterframes(inspect.currentframe()))
[(<frame object at 0x8fc262c>, '<stdin>', 1, '<module>', None, None)]

还有:

>>> import traceback
>>> traceback.extract_stack()
[('<stdin>', 1, '<module>', None)]

更新:

另一个:

>>> import sys
>>> print(sys._getframe().f_trace,sys._getframe().f_code)
(None, <code object <module> at 0x8682a88, file "<stdin>", line 1>)

我不明白这里的细微差别:

  • 堆栈帧
  • 框架对象
  • 堆栈跟踪

更新 2,距离提出问题有一点时间,但非常相关

最佳答案

好吧,因为这似乎更多地是关于一般的堆栈帧/调用堆栈,让我们来看看这个:

def f():
try:
g()
except:
# WE WILL DO THINGS HERE

def g():
h()

def h():
raise Exception('stuff')

#CALL
f()

当我们在 h() 时,call stack 上有 4 帧.

[top level]
[f()]
[g()]
[h()] #<-- we're here

(如果我们试图在堆栈中放入超过 sys.getrecursionlimit() 帧,我们会得到一个 RuntimeError,这是 python 的 StackOverflow 版本 ;-))

“外部”指的是调用堆栈中我们上方的所有内容(字面意思是“向上”方向)。所以按顺序,g,然后是 f,然后是顶层(模块)。同样,“内部”指的是调用堆栈中向下的所有内容。如果我们在 f() 中捕捉到异常,则该回溯对象将引用所有内部堆栈帧,这些帧已展开以使我们到达该点。

def f():
try:
g()
except:
import inspect
import sys
#the third(last) item in sys.exc_info() is the current traceback object
return inspect.getinnerframes(sys.exc_info()[-1])

这给出了:

[(<frame object at 0xaad758>, 'test.py', 3, 'f', ['        g()\n'], 0), 
(<frame object at 0x7f5edeb23648>, 'test.py', 10, 'g', [' h()\n'], 0),
(<frame object at 0x7f5edeabdc50>, 'test.py', 13, 'h', [" raise Exception('stuff')\n"], 0)]

正如预期的那样,三个内框 f、g 和 h。现在,我们可以获取最后一个帧对象(来自 h() 的那个)并请求它的 outer 帧:

[(<frame object at 0x7f6e996e6a48>, 'test.py', 13, 'h', ["    raise Exception('stuff')\n"], 0), 
(<frame object at 0x1bf58b8>, 'test.py', 10, 'g', [' h()\n'], 0),
(<frame object at 0x7f6e99620240>, 'test.py', 7, 'f', [' return inspect.getinnerframes(sys.exc_info()[-1])\n'], 0),
(<frame object at 0x7f6e99725438>, 'test.py', 23, '<module>', ['print(inspect.getouterframes(f()[-1][0]))\n'], 0)]

所以,你去吧,这就是正在发生的一切:我们只是在调用堆栈中导航。为了比较,这里是 traceback.extract_stack(f()[-1][0]) 给出的:

[('test.py', 23, '<module>', 'print(traceback.extract_stack(f()[-1][0]))'), 
('test.py', 7, 'f', 'return inspect.getinnerframes(sys.exc_info()[-1])'),
('test.py', 10, 'g', 'h()'),
('test.py', 13, 'h', "raise Exception('stuff')")]

请注意这里与 getouterframes 相比的倒序,以及减少的输出。事实上,如果你眯起眼睛,这基本上看起来就像一个常规的回溯(嘿,它,只是格式多了一点)。

总结:inspect.getouterframestraceback.extract_stack 都包含重现您在日常回溯中通常看到的所有信息; extract_stack 只是删除对堆栈帧的引用,因为一旦您从给定的帧向外格式化堆栈跟踪,就不再需要它们是很常见的。

关于python - 堆栈和框架有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848391/

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