我正在进行python shell中的计算.我想要的是Matlab样式列表输出,你可以看到所有已经定义到一个点的变量(所以我知道我使用了哪些名称,它们的值等等).
有办法吗,我该怎么做?
一位朋友上周问我如何枚举或列出程序/函数/等中的所有变量.出于调试的目的(基本上获取所有内容的快照,以便您可以查看设置了哪些变量,或者是否设置了它们).我环顾四周,找到了一个比较好的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 …