【问题标题】:templated configuration in python or perl?python或perl中的模板化配置?
【发布时间】:2011-10-14 17:27:55
【问题描述】:

我正在尝试实现模板化配置文件。 我更喜欢 python,但我也会在 perl 中回答。 我使用 perl 作为示例。

我搜索了一下,发现 - python single configuration file - ConfigObj - python configuration file generator - ePerl 但我不能从那些解决我的问题。

我正在尝试生成一个主要采用 INI 格式的配置文件(甚至没有部分):

# Comments
VAR1 = value1
EDITOR = vi

我需要从模板中生成的,我在文本中嵌入了脚本语言:

# Config:
MYPWD = <:   `pwd`  :>

'<:>' 之间的文本将使用脚本语言(python 或 perl)。与模板一样,它的标准输出被捕获并插入到结果文本中。示例中使用的模板基本上是 eperl,但如果可用,我更喜欢 python。

最后,定义的变量应该是可重用的:

# Config:
CODE_HOME = /some/path
CODE_BIN = <:=$CODE_HOME:>/bin

这是我读到的测试源文件:

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# platform.cfg
# This one variable
VAR =value
# this is a templated variable. The langage is perl, but could be python.
HELLO= <: print 'World' :>
# This is a multi-line code which should resolve to a single line value.
LONGER = <:
 if (1) {
    print "abc ";
 }
 $pwd = `/bin/pwd`;
 chomp($pwd);
 print $pwd;
:>
# Another one to test the carriage returns.
MULTIPLE = /<: print "proj" :>/<: print "tahiti":>/<: 
print "pd/1/";
$system = `grep -w VAR platform.cfg | egrep -v 'print|platform.cfg' | cut -d = -f 2-`;
chomp($system);
print $system;
:>
# variables dependent from the previous variable definition
VAR1 = <: print $VAR :>1
# variables dependent from the previous variable definition
VAR2 = <: print $VAR1 :>2
# variables dependent from the previous variable definition
VAR3 = <: print $VAR2 :>3
# variables dependent from the previous variable definition
VAR4 = <: print $VAR3 :>4
# BTW, multi-line comments are significant
# and should be preserved as the documentation for the
# variable just below:
VAR5 = <: print $VAR4 :>5
VAR6 = <: print $VAR5 :>6
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

我希望从脚本中得到这个结果。 我不知道如何让配置文件中定义的变量成为解释器的一部分?

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# platform.cfg
# This one variable
VAR =value
# this is a templated variable. The langage is perl, but could be python.
HELLO= World
# This is a multi-line code which should resolve to a single line value.
LONGER = abc /src/byop/CODE
# Another one to test the carriage returns.
MULTIPLE = /proj/tahiti/pd/1/value
# variables dependent from the previous variable definition
VAR1 = value1
# variables dependent from the previous variable definition
VAR2 = value12
# variables dependent from the previous variable definition
VAR3 = value123
# variables dependent from the previous variable definition
VAR4 = value1234
# BTW, multi-line comments are significant
# and should be preserved as the documentation for the
# variable just below:
VAR5 = value12345
VAR6 = value123456
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

感谢您的建议。

【问题讨论】:

  • 这似乎是一种非常具体和特殊的模板方言。你知道这应该是什么格式吗?
  • @TokenMacGuy:感谢您的评论。我已经编辑了我的问题,以更好地描述我合并了一个配置和一个模板。所以试着回答你的问题:传入文件的格式是一个带括号的配置文件:'<:>'。这些分隔符之间的任何内容都在脚本语言中(python 或 perl,选择一个),并增加了先前在模板中定义的变量应该可以被脚本语言访问的约束。 (这样更清楚吗?)
  • 所以这是你当场编造的模板语言?
  • 另外,chomp() 应该做什么?
  • @TokenMacGuy:我不是当场编造的。我使用了eperl 语法。如果它适用于生成我的配置文件,我会很高兴使用另一种模板语法。 Chomp 是删除尾随换行符的 perl 指令。

标签: python perl templates configuration


【解决方案1】:

我正是为此目的开发了Template::MasonLite。我正在生成大量配置文件(在我的例子中是 Apache 配置),我需要脚本在多个主机上运行而没有额外的依赖项。所以我开发了一个 HTML::Mason 的精简版,它可以直接嵌入到我的脚本中(额外的约 70 行)。 Mason templating syntax 将 Perl 用于任何逻辑(条件、循环等),而不是构成一种全新的语言。

Template::MasonLite 实现不在 CPAN 上(仅在上面的链接中),因为我不想让 CPAN 与另一个模板引擎混淆,而且还不清楚模块应该有什么名称。

在我开发它的时候,我使用的是 cfengine,它缺乏任何健全的模板形式。我已经迁移到包含模板语言的 puppet。对于generating presentation slides,我仍然使用 Template::MasonLite。

【讨论】:

  • 存在于 CPAN 上的轻量级模板系统:Text::Template(可配置分隔符,Perl 语法),Template::Tiny([%%] 分隔符,模板工具包语法)
  • @Grant:我没有看到任何支持将分配反馈回模板引擎,就像在 OP 中一样。
  • @Grant:谢谢,我试过了,但我找不到重用配置变量的方法(又名:VAR2 = )
  • 当我需要做那种事情时,我会在模板顶部的 &lt;%perl&gt; 部分中计算一些值(例如:my $var1 = ...),然后将结果插入到模板(例如:VAR1 = &lt;% $var1 %&gt;)。
【解决方案2】:

如果您不介意使用不同的语法,您可以使用多个模板库,mako 在本质上是相似的,Jinaj2 也很不错。使用久经考验的库!如果你真的想要实现你自己的模板库,这可能会给你一个开始:

import re, StringIO, sys

def exec_block(block, variables):
    """Captures output of exec'd code block"""
    code = compile(block.strip(), '<string>', 'exec')
    _stdout, result = sys.stdout, StringIO.StringIO()
    sys.stdout = sys.__stdout__ = result
    exec(code, variables)
    sys.stdout = sys.__stdout__ = _stdout
    return result.getvalue()

def format_template(template):
    """Replaces code blocks with {0} for string formating later"""
    def sub_blocks(matchobj):
        """re.sub function, adds match to blocks and replaces with {0}"""
        blocks.append(matchobj.group(0)[2:-2].strip())
        return '{0}'

    blocks = []
    template = re.sub(r'<:.+?:>', sub_blocks, template, flags=re.DOTALL).splitlines()
    blocks.reverse()
    return blocks, template

def render_template(blocks, template):
    """renders template, execs each code block and stores variables as we go"""
    composed, variables = [], {}
    for line in template:
        if '{0}' in line:
            replacement = exec_block(blocks.pop(), variables).strip()
            line = line.format(replacement)
        if not line.startswith('#') and '=' in line:
            k, v = [x.strip() for x in line.split('=')]
            variables[k] = v
        composed.append(line)
    return '\n'.join(composed)

if __name__ == '__main__':
    import sys
    with open(sys.argv[1]) as f:
        blocks, template = format_template(f.read())
        print rend_template(blocks, template)

除了代码块使用 Python 之外,基本上与上述类似。每个作业只支持一个块,这实际上对我来说似乎是最好的方法。你可以给它一个配置文件,比如:

VAR = value
LONGER = <:
    print 'something'
:>
VAR1 = <: print VAR :>1
# comment
VAR2 = <: print VAR1 :>2
VAR3 = <: print VAR2 :>3
VAR4 = <: print VAR3 :>4

它会执行每个块为你渲染变量:

VAR = value
LONGER = something
VAR1 = value1
# comment
VAR2 = value12
VAR3 = value123
VAR4 = value1234

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 2022-10-08
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2014-03-09
    • 1970-01-01
    相关资源
    最近更新 更多