嗯,我一直在努力寻找解决方案,因为没有什么是我想要的东西,一切是如此的复杂,我想死......
该解决方案转换一个%something%字符串转换为something值。
它完美,这是一个例子
root_path: /root
script_path: "%root%/scripts"
使用这种方法,script_path将成为/root/scripts。
def replace_values(yaml_file):
def _get(dict, list):
return reduce(lambda d, k: d[k], list, dict)
def _replace(obj):
for k, v in obj.iteritems():
if isinstance(v, dict):
_replace(v)
if isinstance(v, str):
match = re.match(r'%(.*)%', v)
if match:
reference = match.group(1).split('.')
replace = _get(yaml_file, reference)
obj[k] = re.sub(r'%.*%', replace, v)
_replace(yaml_file)
return yaml_file
用法很简单,只需以正常方式加载Yaml文件,然后调用replace。
with open(config_file.get(options.env), 'r') as ymlfile:
config = yaml.load(ymlfile)
config = replace_values(config)
然后我们的新config将存储的替代值,它不会覆盖原有的文件.yml当然。我希望你觉得这很有用,我真的这么做,因为这正是我所需要的。
我用一个百分比%道理,但你可以将其更改为任何你想要的,改变方法,使其与正则表达式的工作(有些令牌是由正则表达式,这就是为什么我用%使用)