List user defined variables, python

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

提交回复
热议问题