How to get all variable and method names used in script

前端 未结 4 1075
攒了一身酷
攒了一身酷 2020-12-25 08:54

It can be weird but I am looking for a way to get automatically all variables and method within a python script.

For example,

a = 1
b = 2
c = 3
myLis         


        
4条回答
  •  猫巷女王i
    2020-12-25 09:24

    There are a lot of variables imported by python so you're going to get a long list, but vars() will work.

    a = 1
    b = 2
    c = 3
    myList = range(10)
    
    def someMethod(x): 
        something = 4
        return something
    
    f = someMethod(b)
    
    print vars()
    

    in terminal:

     $ python temp.py
    {'a': 1, 'c': 3, 'b': 2, 'myList': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'f': 4, '__builtins__': , '__file__': 'temp.py', '__package__': None, 'someMethod': , '__name__': '__main__', '__doc__': None}
    

    EDIT
    You can clean it up a bit by checking for type of variables

    import types
    all_vars = dict(vars())
    for var_name, var in all_vars.iteritems():
        if type(var) not in [types.ModuleType, types.FunctionType] and not var_name.startswith("_"):
            print var_name
    

    in terminal:

    $ python temp.py
    a
    c
    b
    myList
    f
    

提交回复
热议问题