python3 读取配置文件中的参数值替换yaml文件中的占位符(变量) -凯发k8官方网
发布时间:2025/1/21
22
豆豆
凯发k8官方网
收集整理的这篇文章主要介绍了
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
要替换内容的yaml文件:temp.yaml
也就是要将"$$placeholder$$"进行替换。
--- applications: - name: $$name$$-$$datetime$$-$$version$$memory: 2048minstances: 1disk_quota: 2048m ################## ==================================================env:app_id: "$$placeholder$$"table_key: "$$placeholder$$"security: "$$placeholder$$"key: "$$placeholder$$"参数值配置文件:env
app_id=11111111111 table_key=22222222222 security=3333333333333 key=6777777777777python代码
import sys, os from contextlib import exitstack profilelist = {} def propvalue(envfile):with open(envfile) as profile:new_profile = profile.readlines()print(new_profile)for line in new_profile:line_key = line.strip().split("=", 1)[0];profilelist[line_key] = line.strip().split("=", 1)[1] def envreplaceyaml(yamlfile, newyamlfile):try:with exitstack() as stack:yml_file = stack.enter_context(open(yamlfile,'r '))yml_output = stack.enter_context(open(newyamlfile,'w'))yml_file_lines = yml_file.readlines()for line in yml_file_lines:new_line = lineif (new_line.find('$$placeholder$$') > 0):env_list = new_line.split(':')env_name = env_list[0].strip()replacement = ""if env_name in profilelist.keys():replacement = profilelist[env_name];new_line = new_line.replace('$$placeholder$$', replacement)yml_output.write(new_line)except ioerror as e:print("error: " format(str(e)))raiseif __name__ == "__main__":propvalue('env')envreplaceyaml('temp.yaml', 'newtemap.yaml')运行结果
总结
以上是凯发k8官方网为你收集整理的的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: python字符串截取:截取yaml文件
- 下一篇: python3 和python2文件相互