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

有办法吗,我该怎么做?


当前回答

你可以用一些东西:

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

其他回答

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

你可以用一些东西:

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

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

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

打印当地人()

编辑继续评论。

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

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

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