Håk*_*and 2 python introspection
检查模块的文档说:
当以下函数返回"帧记录"时,每个记录都是一个命名元组
FrameInfo(frame, filename, lineno, function, code_context, index).元组包含框架对象,文件名,当前行的行号,函数名称,源代码中的上下文行列表以及该列表中当前行的索引.
什么是"框架对象"?我希望使用这个框架对象从调用者的角度获取变量的值globals():
import my_util
a=3
my_util.get_var('a')
Run Code Online (Sandbox Code Playgroud)
和my_util.py
import inspect
def get_var(name):
print(inspect.stack()[1][0])
Run Code Online (Sandbox Code Playgroud)
来自https://docs.python.org/3/library/inspect.html#types-and-members:
frame f_back next outer frame object (this frame’s caller)
f_builtins builtins namespace seen by this frame
f_code code object being executed in this frame
f_globals global namespace seen by this frame
f_lasti index of last attempted instruction in bytecode
f_lineno current line number in Python source code
f_locals local namespace seen by this frame
f_restricted 0 or 1 if frame is in restricted execution mode
f_trace tracing function for this frame, or None
Run Code Online (Sandbox Code Playgroud)
因此,在my_util.py中获取一些全局变量:
import inspect
def get_var(name):
print(inspect.stack()[1][0].f_globals[name])
Run Code Online (Sandbox Code Playgroud)