用python编译函数读取配置文件

2024-09-29 21:38:38 发布

您现在位置:Python中文网/ 问答频道 /正文

正如在https://prakhar.me/articles/the-compile-function/上给出的,我正在尝试使用Python的compile函数读取配置文件(我正在使用Python版本3.5.3):

def config2dict(fname):
    d = {}
    codeobj = compile(open(fname).read(), 'myconfig', 'exec')
    exec(codeobj, d)
    return d

dd = config2dict("myconfig.cfg")
print(dd)

那个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

问题出在哪里,如何解决?你知道吗


Tags: 文件hostreaddblineopencfgfname
1条回答
网友
1楼 · 发布于 2024-09-29 21:38:38

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)

相关问题 更多 >

    热门问题