Skip to main content
 首页 » 编程设计

python之inspect.getouterframes() 函数的 'index' 术语是什么

2025年05月04日8虾米哥

我在 python 上做了一个“help(inspect.getouterframes)”,这是它给我的:

getouterframes(frame, **context**=1) 
Get a list of records for a frame and all higher (calling) 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 
 
def f(): 
    # prev 
    return sys._getframe() 
    # next 
 
# prev 
framelist = inspect.getouterframes(f(), 3) 
# next 
 
for frame in framelist: 
    print frame[3], "context:\n" 
    for i, line in enumerate(frame[-2]): 
        print line.rstrip(), 
        if i == frame[-1]: 
            print ' *** index ***' 
        else: 
            print 
    print 

输出:

f context: 
 
    # prev 
    return sys._getframe()  *** index *** 
    # next 
 
<module> context: 
 
# prev 
framelist = inspect.getouterframes(f(), 3)  *** index *** 
# next