一位朋友上周问我如何枚举或列出程序/函数/等中的所有变量.出于调试的目的(基本上获取所有内容的快照,以便您可以查看设置了哪些变量,或者是否设置了它们).我环顾四周,找到了一个比较好的Python方法:
#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
"2":"b"}
foo4 = "1+1"
for name in dir():
myvalue = eval(name)
print name, "is", type(name), "and is equal to ", myvalue
这将输出如下内容:
__builtins__ is <type 'str'> and is equal to <module '__builtin__' (built-in)> __doc__ is <type 'str'> and is equal to None __file__ is <type 'str'> and is equal to ./foo.py __name__ is <type 'str'> and is equal to __main__ foo1 is <type 'str'> and is equal to …
我们假设我有以下文件结构:
data.py
foo = []
bar = []
abc = "def"
Run Code Online (Sandbox Code Playgroud)
core.py
import data
# do something here #
# a = ...
print a
# ['foo', 'bar', 'abc']
Run Code Online (Sandbox Code Playgroud)
我需要获取data.py文件中定义的所有变量.我怎样才能做到这一点?我可以使用dir(),但它返回模块的所有属性,包括__name__等等.