我目前正在使用 Python 库 configparser:
from configparser import ConfigParser, ExtendedInterpolation
我发现 ExtendedInterpolation 非常有用,因为它避免了必须在多个地方重新输入常量的风险。
我现在需要使用 Json 文档作为配置的基础,因为它提供了更多结构。
import json
from collections import OrderedDict
def get_json_config(file):
"""Load Json into OrderedDict from file"""
with open(file) as json_data:
d = json.load(json_data, object_pairs_hook=OrderedDict)
return d
对于实现 configparser 风格的 ExtendedInterpolation 的最佳方式,有人有什么建议吗?
例如,如果 Json 中的节点包含值 ${home_dir}/lumberjack,这将复制根节点 home_dir 并取值“lumberjack”?
最佳答案
尝试使用string.Template
。但我不确定这是否是你的需要。有一个包可以做到这一点。贝娄是我应该做的。
config.json
{
"home_dir": "/home/joey",
"class_path": "/user/local/bin",
"dir_one": "${home_dir}/dir_one",
"dir_two": "${home_dir}/dir_two",
"sep_path_list": [
"${class_path}/python",
"${class_path}/ruby",
"${class_path}/php"
]
}
python 代码:
import json
from string import Template
with open("config.json", "r") as config_file:
config_content = config_file.read()
config_template = Template(config_content)
mid_json = json.loads(config_content)
config = config_template.safe_substitute(mid_json)
print config
这可以替换json文件中定义的key。
关于Python Json 配置 'Extended Interpolation',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38716890/