欢迎访问 生活随笔!

凯发ag旗舰厅登录网址下载

当前位置: 凯发ag旗舰厅登录网址下载 > 编程语言 > >内容正文

python

python3 读取配置文件中的参数值替换yaml文件中的占位符(变量) -凯发ag旗舰厅登录网址下载

发布时间:2025/1/21 22 豆豆
凯发ag旗舰厅登录网址下载 收集整理的这篇文章主要介绍了 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

要替换内容的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=6777777777777

python代码

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')

运行结果

总结

以上是凯发ag旗舰厅登录网址下载为你收集整理的的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发ag旗舰厅登录网址下载网站内容还不错,欢迎将凯发ag旗舰厅登录网址下载推荐给好友。

网站地图