用python中的编译函数读取配置文件
如上所述,我正在尝试使用Python的用python中的编译函数读取配置文件,python,Python,如上所述,我正在尝试使用Python的compile函数读取配置文件(我正在使用Python版本3.5.3): myconfig.cfg文件包含: DB_HOST = 172.123.125.34 DB_USER = app_user DB_PASS = lly4paw 但是,我得到了以下错误: Traceback (most recent call last): File "mytest.py", line 19, in <module> dd = config2di
compile
函数读取配置文件(我正在使用Python版本3.5.3):
myconfig.cfg文件包含:
DB_HOST = 172.123.125.34
DB_USER = app_user
DB_PASS = lly4paw
但是,我得到了以下错误:
Traceback (most recent call last):
File "mytest.py", line 19, in <module>
dd = config2dict("myconfig.cfg")
File "mytest.py", line 14, in config2dict
codeobj = compile(open(fname).read(), 'myconfig', 'exec')
File "myconfig", line 1
DB_HOST = 172.123.125.34
回溯(最近一次呼叫最后一次):
文件“mytest.py”,第19行,在
dd=config2dict(“myconfig.cfg”)
config2dict中第14行的文件“mytest.py”
codeobj=compile(open(fname).read(),'myconfig','exec')
文件“myconfig”,第1行
DB_HOST=172.123.125.34
问题在哪里?如何解决?应在编译的代码中设置d dict,并且应将数据拆分以设置dict
def config2dict(fname):
d = {}
codeobj = compile("txt=open(fname).read()\nd.update(dict([tuple([y.strip() for y in x.split(\"=\")]) for x in txt.split(\"\\n\") if x!=\"\"]))", 'myconfig', 'exec')
exec(codeobj)
return d
dd = config2dict("myconfig.cfg")
print(dd)
好的,在仔细看了你的问题之后,你的字符串周围似乎缺少了引号
DB_HOST=172.123.125.34
应该是DB_HOST=“172.123.125.34”
,否则解析器会抛出错误。我必须将所有值保留在引号中。但现在返回的字典包含大量数据-似乎整个环境都被添加到字典中。我看到在我尝试代码时,字典中添加了一个额外的键,\uuuuuuu builtins\uuuuu
。在从config2dict
返回之前,您可以尝试d.pop(“\uu内置项”\uuuuuu',无)
来摆脱它。当然,我仔细检查了,它在我的计算机win7上工作。复制代码时,请注意空格。如果您有错误,错误是什么?我使用“python compiletest.py”运行compiletest.py,compiletest.py的内容是以前粘贴的代码。您现在已经更改了答案。我在对参数对进行元组化之前添加了strip(),因为数据包含“=”周围的空格,这只是为了使它更好。使用此代码,我得到了一个空字典:{}
。我刚刚复制了你的代码,并用问题中提到的cfg文件运行了你的代码。怎么可能呢?我复制了myconfig.cfg,所以,内容应该是相同的。而且,我在linux和windows上进行了尝试,这两种系统都可以工作,输出是一个dict,其中包含myconfig.cfg中的数据。如果d仍然是空的,那么似乎没有执行codeobj,您是否尝试清理编译后的文件?
def config2dict(fname):
d = {}
codeobj = compile("txt=open(fname).read()\nd.update(dict([tuple([y.strip() for y in x.split(\"=\")]) for x in txt.split(\"\\n\") if x!=\"\"]))", 'myconfig', 'exec')
exec(codeobj)
return d
dd = config2dict("myconfig.cfg")
print(dd)