本文介绍了在Python中加载与Jinja2嵌套的YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个YAML文件( all.yaml
),看起来像:
I have a YAML file (all.yaml
) that looks like:
...
var1: val1
var2: val2
var3: {{var1}}-{{var2}}.txt
...
如果我像这样在Python中加载它:
If I load it in Python like this:
import yaml
f = open('all.yaml')
dataMap = yaml.safe_load(f)
f.close()
print(dataMap["var3"])
输出为 {{var1}}-{{var2}}。txt
而不是 val1-val2.txt
。
是否可以用值替换嵌套的变量?
Is it possible to replace the nested vars with the value?
我尝试加载:
import jinja2
templateLoader = jinja2.FileSystemLoader( searchpath="/path/to/dir" )
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "all.yaml"
template = templateEnv.get_template( TEMPLATE_FILE )
不再抛出异常,现在我被卡住了,必须研究
The exception is no longer thrown, now I am stuck and have to research how to proceed.
推荐答案
首先定义一个 Undefined
类并加载yaml获得已知值。然后再次加载它并渲染为已知值。
First define an Undefined
class and load yaml to get known values. Then load it again and render with known values.
#!/usr/bin/env python
import yaml
from jinja2 import Template, Undefined
str1 = '''var1: val1
var2: val2
var3: {{var1}}-{{var2}}.txt
'''
class NullUndefined(Undefined):
def __getattr__(self, key):
return ''
t = Template(str1, undefined=NullUndefined)
c = yaml.safe_load(t.render())
print t.render(c)
运行它:
$ ./test.py
var1: val1
var2: val2
var3: val1-val2.txt
这篇关于在Python中加载与Jinja2嵌套的YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!