【问题标题】:resolving YAML files and substituting into templates解析 YAML 文件并替换为模板
【发布时间】:2017-02-25 01:00:52
【问题描述】:

我在配置文件夹中有一堆 YAML 文件,在模板文件夹中有一堆模板。是否有一个简单的衬线或函数可用于解析 YAML 文件并替换模板文件以生成可执行脚本

输入:
配置文件夹:config/yaml1config/yaml2config/yaml3.
模板:template/template1template/template2template3

输出
scripts/script1, script2, script3

脚本数=模板数

有两种类型的模板

直接替换 示例

YAML1:
    Titles:4
    SubTitles:10
Template1:
Number of Titles {Titles} where as Number of Subtitles is {SubTitles}

其他模板是嵌套的。基本上模板需要基于 YAML 循环 示例:

YAML2:
    Book: "The Choice of using Choice"
        Author: "Unknown1"
    Book: "Chasing Choices"
        Author:"Known2"
Template2
Here are all the Books with Author Info
The author of the {Book} is {Author}

【问题讨论】:

    标签: python templates yaml


    【解决方案1】:

    我不完全确定您要完成什么,我不知道您所说的可执行脚本是什么意思?如果我解释正确,您可能会受益于查看 PyYAML Docs。具体来说,YAML Tags and Python Types 部分。

    有几个 YAML 标签允许调用 python 模块或包,包参数由它下面的嵌套 YAML 标签填充。因此,您必须编写一个使用 YAML kwargs 的类或函数,但您只需在 YAML 配置中使用这样的一行调用它,

    !!python/object/apply:module.function [argument, ...] 
    

    虽然您也可以从查看 python 文档中关于Constructors, Representers and Resolversstring.Template 的部分。

    理论上,您应该能够从 YAML 文件中调用substitution() 函数。

    【讨论】:

      【解决方案2】:

      YAML 对模板一无所知,您也没有指定需要更新哪种模板。但是,如果您使用的模板语言假定其替换值来自 Python dict 中的键值对,那么您可以在 YAML 文件中指定顶级映射,加载该映射(将被构造成 Python dict),然后将其输入模板引擎。

      您仍然需要遍历文件,因此几行代码比在单行中实现上述内容更有可能。

      【讨论】:

        【解决方案3】:

        这是一种模板语言,它将 python 的大部分功能暴露在模板中,并且可以很好地处理 yaml 文件:

        https://pypi.org/project/smx/

        应该能够帮助在 yml 中完成模板任务。

        【讨论】:

          猜你喜欢
          • 2014-11-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-25
          • 2014-01-25
          相关资源
          最近更新 更多