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

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

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

最佳答案

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)

关于python - 在python中使用编译功能读取配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48471900/

相关文章:

python - Flask 无法运行 db migrate - NameError : name 'conn_uniques' is not defined

python - 在使用 python、django 或基于 shell 的工具进行重定向后,如何捕获最终 url?

python - 我一直在 pygame 中从事一个项目,但即使没有出现错误,玩家移动似乎也不起作用

python - Python 的可嵌入工作流/BPM 库?

python3用单反斜杠替换双反斜杠

Python:使用正则表达式检查 str

python - Tensorflow - 显示和手动修改学习模型的权重并导出以供进一步重新学习

python - Python 中用参数修饰是什么意思?

python - 如何在 Pygame 中设置延迟/冷却时间?

python - 有没有办法记录在 django View 中进行的查询总数?