列出用户定义的变量,python [英] List user defined variables, python
本文介绍了列出用户定义的变量,python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试遍历 Python 脚本中设置的变量.我遇到了以下情况:
I am trying to iterate through the variables set in a python script. I came across the following:
在第一个例子中:
#!/us/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"
for name in dir():
myvalue = eval(name)
print name, "is", type(name), "and is equal to ", myvalue
它列出了存储在内存中的所有变量.我想隔离我在脚本中创建的变量,而不是列出默认创建的系统变量.有没有办法做到这一点?
It lists all the variables stored in memory. I want to isolate the variables I have created in my script and not list the system variables created by default. Is there any way to do this?
推荐答案
如果您不将任何下划线放在变量前,您可以这样做:
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
这篇关于列出用户定义的变量,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文