Skip to main content
 首页 » 编程设计

python之在python中使用编译功能读取配置文件

2025年01月19日11bonelee

在 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 

问题出在哪里,如何解决?

请您参考如下方法:

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)