inspect module的文档说:
当以下函数返回“帧记录”时,每条记录都是a 命名为元组
globals()
。元组包含框架对象,文件名,行 当前行号,函数名,行列表 来自源代码的上下文,以及当前行的索引 那份清单。
实际上是什么"框架对象" ?我希望使用这个框架对象从调用者import my_util
a=3
my_util.get_var('a')
获取变量的值:
import inspect
def get_var(name):
print(inspect.stack()[1][0])
和 my_util.py
label
答案 0 :(得分:5)
来自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
因此要在my_util.py中获取一些全局变量:
import inspect
def get_var(name):
print(inspect.stack()[1][0].f_globals[name])