如何读取模板中的多行并替换值?

How to read multiple lines in a template and substitute values?

我有一段标准文本有多行,格式如下:

owner: oracle
date_conditions: 1
    timezone: US/Eastern
    std_out_file: "/app/local/job.log"
    machine: rachost

我想使用上面的文本,并根据需要更改机器和时区。 如何使用 python 来定义这是一个模板并替换各种值? 我在 string.Template 中遇到了替换选项。但这似乎只适用于单行。

string.Templateclass可以处理由多行组成的字符串。

例如:

from string import Template

template = Template('''\
owner: oracle
date_conditions: 1
    timezone: $tz
    std_out_file: "/app/local/job.log"
    machine: $mach
''')

result = template.substitute(tz='US/Pacific', mach='foobar')
print(result, end='')

打印:

owner: oracle
date_conditions: 1
    timezone: US/Pacific
    std_out_file: "/app/local/job.log"
    machine: foobar