List user defined variables, python

后端 未结 5 1502
天涯浪人
天涯浪人 2021-01-06 05:39

I am trying to iterate through the variables set in a python script. I came across the following:

Enumerate or list all variables in a program of [your favorite lang

相关标签:
5条回答
  • 2021-01-06 06:05

    I wanted something more along the lines of matlab 'whos', so I baked this up: gist here

    import __main__
    def whos(lss):
     fil = __main__.__file__
     thisthinghere = open(fil).read().split("\n")
     vs = []
     for l in thisthinghere:
        if l.find("=") > -1:
            vs.append(l.split("=")[0].strip())
     keys = lss.keys()
     out = {}
     for v in vs:
        try: 
            out[v] = lss[v]
        except:
            "not in list"
     keys = out.keys()
     keys.sort()
     for k in keys:
        val = str(out[k])
        if len (val) > 10:
            if val[-1] == ")":val = val[0:10]+"..."+val[-10:]
            elif val[-1] == "]" :val = val[0:10]+"..."+val[-10:]
            else: val = val[0:10]
        print k,":",val
    
     return out
    
    #import into your script and call with whos(locals())
    

    it seems to work. it will print the variable space, and it returns it as a dictionary for easy pickling/jsoning.

    0 讨论(0)
  • 2021-01-06 06:07

    You can strip out variables that are included in your module by default by checking if they are in the builtin __builtins__ module, like this:

    >>> x = 3
    >>> set(dir()) - set(dir(__builtins__))
    set(['__builtins__', 'x'])
    

    The only thing this doesn't strip out is __builtins__ itself, which is easy to special case.

    Also note that this won't work if you have re-defined any builtin names. You shouldn't do this in practice, but a lot of people do, many by accident.

    0 讨论(0)
  • 2021-01-06 06:10

    Here is solution.

    #!/us/bin/python    
    
    not_my_data = set(dir())
    
    foo1 = "Hello world"
    foo2 = "bar"
    foo3 = {"1":"a", "2":"b"}
    foo4 = "1+1"
    
    my_data = set(dir()) - not_my_data
    
    for name in my_data :
        myvalue = eval(name)
        print name, "is", type(name), "and is equal to ", myvalue
    

    but this is bad practice.

    You should use something like

    #!/us/bin/python    
    my_data = dict()                                                                                   
    my_data['foo1'] = "Hello world"
    my_data['foo2'] = "bar"
    my_data['foo1'] = {"1":"a", "2":"b"}
    my_data['foo1'] = "1+1"
    
    for name in my_data :
        myvalue = eval(my_data[name])
        print name, "is", type(name), "and is equal to ", myvalue
    
    0 讨论(0)
  • 2021-01-06 06:13

    The question title leads me to see this. But this is not what I wanted.

    self-answering is below

    [s for s in dir() if not '__' in s]
    
    0 讨论(0)
  • 2021-01-06 06:26

    If you don't put any underscores in front of your variables you could do:

    #!/us/bin/python                                                                                    
    
    foo1 = "Hello world"
    foo2 = "bar"
    foo3 = {"1":"a", "2":"b"}
    foo4 = "1+1"
    
    for name in dir():
        if not name.startswith('__'):
            myvalue = eval(name)
            print name, "is", type(myvalue), "and is equal to ", myvalue
    
    0 讨论(0)
提交回复
热议问题