List user defined variables, python

后端 未结 5 1522
天涯浪人
天涯浪人 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.

提交回复
热议问题