我目前正在python shell中进行计算。我想要的是Matlab风格的列表,在那里你可以看到所有已经定义到某一点的变量(所以我知道我使用了哪些名称,它们的值等等)。
有办法吗,我该怎么做?
我目前正在python shell中进行计算。我想要的是Matlab风格的列表,在那里你可以看到所有已经定义到某一点的变量(所以我知道我使用了哪些名称,它们的值等等)。
有办法吗,我该怎么做?
要得到这些名字:
for name in vars().keys():
print(name)
要得到这些值:
for value in vars().values():
print(value)
Vars()还接受一个可选参数,以确定对象本身中定义了哪些Vars。
打印当地人()
编辑继续评论。
为了在打印时看起来更漂亮:
import sys, pprint
sys.displayhook = pprint.pprint
locals()
这样打印出来的效果会更垂直。
请记住,dir()将返回所有当前导入和变量。
如果你只是想要你的变量,我会建议一个容易从dir提取的命名方案,如varScore, varNames等。
这样,你可以简单地这样做:
for vars in dir():
if vars.startswith("var"):
print vars
Edit
如果你想列出所有变量,但排除导入的模块和变量,例如:
__builtins__
你可以这样使用:
import os
import re
x = 11
imports = "os","re"
for vars in dir():
if vars.startswith("__") == 0 and vars not in imports:
print vars
正如您所看到的,它将显示变量“imports”,因为它是一个变量(嗯,一个元组)。一个快速的解决方法是将单词“imports”添加到imports元组本身!
如果可能,您可能希望使用IPython。
为了获得当前所有用户定义变量的列表,IPython提供了一个名为who的magic命令(magics必须以%字符作为前缀,除非启用了automagic特性):
In [1]: foo = 'bar'
In [2]: %who
foo
你可以使用whos魔术来获得更多细节:
In [3]: %whos
Variable Type Data/Info
----------------------------
foo str bar
还有很多其他的魔法可用。IPython基本上是Python解释器的类固醇。一个方便的魔法是存储,它允许您在会话之间保存变量(使用pickle)。
注意:我没有与IPython开发-只是一个满意的用户。
编辑:
你可以在IPython文档中找到所有神奇的命令。
本文还有一个关于在Jupyter Notebook中使用魔法命令的有用部分
这必须在交互式shell中定义:
def MyWho():
print [v for v in globals().keys() if not v.startswith('_')]
以下面的代码为例:
>>> import os
>>> import sys
>>> a = 10
>>> MyWho()
['a', 'MyWho', 'sys', 'os']
更聪明一点的方法(python 3):
def printvars():
tmp = globals().copy()
[print(k,' : ',v,' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]
或者如果你想输出一个对象的变量:
def printObj(Obj, OutputMax=100):
tmp = Obj.__dict__
[print(k,' : ',str(v)[:OutputMax],' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]
在我的Python 2.7解释器中,MATLAB中存在的whoos命令也存在于Python中。它显示了与MATLAB模拟相同的细节(变量名、类型和值/数据)。
请注意,在Python解释器中,它列出了“交互式名称空间”中的所有变量。
正如RedBlueThing和analog所说:
Dir()给出了范围内变量的列表 Globals()给出一个全局变量字典 Locals()给出一个局部变量字典
使用交互式shell(版本2.6.9),在创建变量a = 1和b = 2之后,运行dir()会得到
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']
运行locals()会得到
{'a': 1, 'b': 2, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
在这种情况下,运行globals()得到的答案与locals()完全相同。
我还没有讲到任何模块,所以所有的变量都可以作为局部变量和全局变量使用。Locals()和globals()列出变量的值和名称;Dir()只列出名称。
如果我导入一个模块并在模块内运行locals()或globals(), dir()仍然只给出少量变量;它将__file__添加到上面列出的变量中。Locals()和globals()也列出了相同的变量,但在打印__builtin__的字典值的过程中,它列出了更多的变量:内置函数、异常和类型,如"'type': <type 'type'>",而不仅仅是上面所示的简短的<模块'__builtin__'(内置)>。
有关dir()的更多信息,请参阅新墨西哥理工学院的Python 2.7快速参考或ibiblio.org的dir()函数。
有关locals()和globals()的更多信息,请参阅Dive Into Python中的locals和globals,以及新墨西哥理工学院关于globals的页面。
[Comment: @Kurt: You gave a link to enumerate-or-list-all-variables-in-a-program-of-your-favorite-language-here but that answer has a mistake in it. The problem there is: type(name) in that example will always return <type 'str'>. You do get a list of the variables, which answers the question, but with incorrect types listed beside them. This was not obvious in your example because all the variables happened to be strings anyway; however, what it's returning is the type of the name of the variable instead of the type of the variable. To fix this: instead of print type(name) use print eval('type(' + name + ')'). I apologize for posting a comment in the answer section but I don't have comment posting privileges, and the other question is closed.]