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

有办法吗,我该怎么做?


当前回答

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

其他回答

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

要得到这些名字:

for name in vars().keys():
  print(name)

要得到这些值:

for value in vars().values():
  print(value)

Vars()还接受一个可选参数,以确定对象本身中定义了哪些Vars。

Globals()、locals()、vars()和dir()都可以帮到你。

请记住,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元组本身!

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