简体   繁体   English

从文件读取python变量

[英]Read python variables from a file

I would like to read all variables stored in a file like this : 我想读取存储在这样的文件中的所有变量:

var1=val1
var2=val2
..etc

Is there a way to access to a metadata where I can find and list all variables without knowing their names? 有没有一种方法可以访问元数据,因此我可以在不知道变量名的情况下查找并列出所有变量? In my script I am using execfile("myFile.txt") . 在我的脚本中,我正在使用execfile("myFile.txt")

execfile actually supports what you want to do. execfile实际上支持您要执行的操作。

global_vars = {}
local_vars = {}

execfile("myFile.txt", global_vars, local_vars)

# local_vars now contains the variables defined in the file.
print local_vars

You can use eval() to set the variables or you can turn the file to a dictionary, I think the second solution is more safe than the first one ! 您可以使用eval()设置变量,也可以将文件转换为字典,我认为第二种解决方案比第一种更安全! You can also make a class and use setattr(self, name, value) to attach the variables to that class dynamically and using the parsed strings. 您还可以创建一个类,并使用setattr(self,name,value)将变量动态地和使用解析的字符串附加到该类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM