当前位置 : 首页 » 互动问答 » 正文

Viewing all defined variables

分类 : 互动问答 | 发布时间 : 2009-03-11 10:32:55 | 评论 : 10 | 浏览 : 251118 | 喜欢 : 192

I'm currently working on a computation in python shell. What I want to have is Matlab style listout where you can see all the variables that have been defined up to a point (so I know which names I've used, their values and such).

Is there a way, and how can I do that?

回答(10)

  • 1楼
  • Couple of things you could use:

    • dir() will give you the list of in scope variables:
    • globals() will give you a dictionary of global variables
    • locals() will give you a dictionary of local variables
  • 2楼
  • If possible, you may want to use IPython.

    To get a list of all current user-defined variables, IPython provides a magic command named who (magics must be prefixed with the modulo character unless the automagic feature is enabled):

    In [1]: foo = 'bar'
    In [2]: %who
    foo
    

    You can use the whos magic to get more detail:

    In [3]: %whos
    Variable   Type    Data/Info
    ----------------------------
    foo        str     bar
    

    There are a wealth of other magics available. IPython is basically the Python interpreter on steroids. One convenient magic is store, which lets you save variables between sessions (using pickle).

    If you have a few minutes, check out Jeff Rush's excellent IPython demo screencasts.

    Note: I am not associated with IPython Dev - just a satisfied user.

  • 3楼
  • As RedBlueThing and analog said:

    • dir() gives a list of in scope variables
    • globals() gives a dictionary of global variables
    • locals() gives a dictionary of local variables

    Using the interactive shell (version 2.6.9), after creating variables a = 1 and b = 2, running dir() gives

    ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']
    

    running locals() gives

    {'a': 1, 'b': 2, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
    

    Running globals() gives exactly the same answer as locals() in this case.

    I haven't gotten into any modules, so all the variables are available as both local and global variables. locals() and globals() list the values of the variables as well as the names; dir() only lists the names.

    If I import a module and run locals() or globals() inside the module, dir() still gives only a small number of variables; it adds __file__ to the variables listed above. locals() and globals() also list the same variables, but in the process of printing out the dictionary value for __builtin__, it lists a far larger number of variables: built-in functions, exceptions, and types such as "'type': <type 'type'>", rather than just the brief <module '__builtin__' (built-in)> as shown above.

    For more about dir() see Python 2.7 quick reference at New Mexico Tech or the dir() function at ibiblio.org.

    For more about locals() and globals() see locals and globals at Dive Into Python and a page about globals at New Mexico Tech.

    [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.]

  • 4楼
  • To get the names:

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

    To get the values:

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

    vars() also takes an optional argument to find out which vars are defined within an object itself.

  • 5楼
  • print locals()

    edit continued from comment.

    To make it look a little prettier when printing:

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

    That should give you a more vertical printout.

  • 6楼
  • keep in mind dir() will return all current imports, AND variables.

    if you just want your variables, I would suggest a naming scheme that is easy to extract from dir, such as varScore, varNames, etc.

    that way, you can simply do this:

    for vars in dir():
     if vars.startswith("var"):
       print vars
    

    Edit

    if you want to list all variables, but exclude imported modules and variables such as:

    __builtins__
    

    you can use something like so:

    import os
    import re
    
    x = 11
    imports = "os","re"
    
    for vars in dir():
        if vars.startswith("__") == 0 and vars not in imports:
            print vars
    

    as you can see, it will show the variable "imports" though, because it is a variable (well, a tuple). A quick workaround is to add the word "imports" into the imports tuple itself!

  • 7楼
  • a bit more smart (python 3) way:

    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__')]
    
  • 8楼
  • In my Python 2.7 interpreter, the same whos command that exists in MATLAB exists in Python. It shows the same details as the MATLAB analog (variable name, type, and value/data).

    In the Python interpreter, whos lists all variables in the "interactive namespace".

  • 9楼
  • globals(), locals(), vars(), and dir() may all help you in what you want.

  • 10楼
  • def MyWho():
         print [v for v in globals().keys() if not v.startswith('_')]
    

    This has to be defined in the interactive shell.

    import os, a = 10, import sys, MyWho() then gives

    ['a', 'MyWho', 'sys', 'os']

相关阅读:

raw_input function in Python

How to import the class within the same directory or sub directory?

How to return dictionary keys as a list in Python?

Python `if x is not None` or `if not x is None`?

Assign output of os.system to a variable and prevent it from being displayed on the screen

How can I reverse a list in Python?

What are the differences between type() and isinstance()?

How to install packages using pip according to the requirements.txt file from a local directory?

How to lowercase a string in Python?

Correct way to write line to file?