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

时间:2018-01-27 02:00:27

标签: 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

问题在哪里以及如何解决?

1 个答案:

答案 0 :(得分:1)

应该在编译的代码中设置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)