Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想知道是否有办法在配置文件中建立字典并使用 python 配置解析器来读取它?
谢谢。
使用eval并简单地执行配置文件。
eval
with open('the_config','r') as config_file: config= eval( config_file.read() )
你会看到评论告诉你这是邪恶的、安全漏洞和许多其他事情。但是,它与您的 Python 源代码一样安全。
configparser不支持,但也许您可能有兴趣查看该json模块。
configparser
json
改编官方文档中的一个例子:
>>> import json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) >>> print(s) { "4": 5, "6": 7 } >>> json.loads(s) {'4': 5, '6': 7}