Python 使用Jinja2为多个配置文件序列化YAML数据

Python 使用Jinja2为多个配置文件序列化YAML数据,python,yaml,jinja2,pyyaml,Python,Yaml,Jinja2,Pyyaml,我已经能够将YAML文档中的数据加载到配置文件中 亚马尔: Python脚本: #Import necessary functions from Jinja2 module from jinja2 import Environment, FileSystemLoader #Import YAML module import yaml import sys ALLOWED_ARGS = set(['template', 'data']) def print_usage(): pri

我已经能够将YAML文档中的数据加载到配置文件中

亚马尔:

Python脚本:

#Import necessary functions from Jinja2 module
from jinja2 import Environment, FileSystemLoader

#Import YAML module
import yaml

import sys

ALLOWED_ARGS = set(['template', 'data'])

def print_usage():
    print('Wrong arguments: Usage: configplate.py --template=<template.jinja> --data=<data.yaml>')

def load_args(args):
    out = {}
    for arg in args:
        if arg == __file__: #ignore the filename argument
            continue
        args_splited = arg.split('=')
        out[args_splited[0].lstrip('-')] = args_splited[1]
    if set(out.keys()) != set(ALLOWED_ARGS):
        print_usage()
        raise ValueError('Required argument not present.')
    return out

def make(template, data):
    #Load data from YAML into Python dictionary
    config_data = yaml.load(open(data))

    #Load Jinja2 templates
    env = Environment(loader = FileSystemLoader('.'), trim_blocks=True, lstrip_blocks=True)
    template = env.get_template(template)

    #Render the template with data and print the output
    return template.render(config_data)

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print_usage()
    else:
        args = load_args(sys.argv)
        res = make(args['template'], args['data'])
        print(res)
#从Jinja2模块导入必要的功能
从jinja2导入环境,FileSystemLoader
#导入YAML模块
进口yaml
导入系统
允许的参数=set(['template','data'])
def print_用法():
print('错误参数:用法:configplate.py--template=--data=')
def加载参数(参数):
out={}
对于args中的arg:
如果arg==\uuuuuuuuuuuuuuuuuuuuuuuuuu:#忽略filename参数
持续
args_splited=arg.split('='))
out[args_splited[0]。lstrip('-')]=args_splited[1]
如果设置(out.keys())!=设置(允许的参数):
打印_用法()
raise VALUERROR('所需参数不存在')
返回
def品牌(模板、数据):
#将数据从YAML加载到Python字典中
config_data=yaml.load(打开(数据))
#加载Jinja2模板
env=Environment(loader=FileSystemLoader('.')、trim_blocks=True、lstrip_blocks=True)
模板=环境获取模板(模板)
#使用数据呈现模板并打印输出
return template.render(配置_数据)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
如果len(sys.argv)!=三:
打印_用法()
其他:
args=加载参数(sys.argv)
res=make(args['template'],args['data'])
打印(res)
配置文件:

<add name="Cloud" connectionString="{{ x }}" />

我现在面临的问题是,我不能将同一个YAML加载到多个配置文件中。我想同时填充第二个配置文件

配置文件2:

<add name="Cloud" connectionString="{{ y }}" />


如何将其添加到同一个python脚本中?我也不需要在控制台上设置配置文件,我可以简单地将它们的路径放入脚本中。

因为您想要处理多个模板,所以需要使您的
加载参数能够处理多个
--template=
参数/选项。 我修改了您的
load_args
以返回一个带有列表值的dict,但是对允许的参数数量(多个模板,单个YAML文件)的检查是粗糙的

为了处理命令行,您应该查看标准模块,其中您可以指出每个参数/选项可以出现多次

由于要重用来自YAML的数据,因此只需在调用
make()
之外加载一次没有理由不使用
安全加载()
而不是记录在案的不安全加载()

与:


(顺便说一句,查找
的共轭来拆分
,没有“拆分”(或“拆分”)之类的东西,即“已拆分”的东西)

<add name="Cloud" connectionString="{{ y }}" />
#Import necessary functions from Jinja2 module
from jinja2 import Environment, FileSystemLoader

#Import YAML module
import yaml

import sys

ALLOWED_ARGS = set(['template', 'data'])

def print_usage():
    print('Wrong arguments: Usage: configplate.py --template=<template.jinja> --data=<data.yaml>')

def load_args(args):
    out = {}
    for arg in args:
        if arg == __file__: #ignore the filename argument
            continue
        args_split = arg.split('=', 1)
        out.setdefault(args_split[0].lstrip('-'), []).append(args_split[1])
    if (set(out.keys()) != set(ALLOWED_ARGS)) or len(out['data']) != 1:
        print_usage()
        raise ValueError('Required argument not present.')
    return out

def make(template, data):
    #Load Jinja2 templates
    env = Environment(loader = FileSystemLoader('.'), trim_blocks=True, lstrip_blocks=True)
    template = env.get_template(template)

    #Render the template with data and print the output
    return template.render(data)

sys.argv=[
    __file__,
    '--template=config1.jinja',
    '--template=config2.jinja',
    '--data=data.yaml'
]

if __name__ == '__main__':
    if len(sys.argv) < 4:
        print_usage()
    else:
        args = load_args(sys.argv)
        # Load data from YAML into Python dictionary **once** and **safely**
        config_data = yaml.safe_load(open(args['data'][0]))
        for template_file in args['template']:
            res = make(template_file, config_data)
            print(res)
<add name="Cloud" connectionString="key1" />
<add name="Cloud" connectionString="key2" />
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--template', action='append', nargs='+', required=True)
    parser.add_argument('--data', required=True)
    args = parser.parse_args()

    # Load data from YAML into Python dictionary **once** and **safely**
    config_data = yaml.safe_load(open(args.data))
    for template_file in args.template:
        res = make(template_file, config_data)
        print(res)