我目前正在python shell中进行计算。我想要的是Matlab风格的列表,在那里你可以看到所有已经定义到某一点的变量(所以我知道我使用了哪些名称,它们的值等等)。

有办法吗,我该怎么做?


当前回答

正如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.]

其他回答

这必须在交互式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']

你可以用一些东西:

Dir()将为您提供范围内变量的列表 Globals()将为您提供一个全局变量字典 Locals()将为您提供一个局部变量字典

在我的Python 2.7解释器中,MATLAB中存在的whoos命令也存在于Python中。它显示了与MATLAB模拟相同的细节(变量名、类型和值/数据)。

请注意,在Python解释器中,它列出了“交互式名称空间”中的所有变量。

更聪明一点的方法(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__')]

打印当地人()

编辑继续评论。

为了在打印时看起来更漂亮:

import sys, pprint
sys.displayhook = pprint.pprint
locals()

这样打印出来的效果会更垂直。