use*_*332 5 python yaml python-3.6 f-string
如果我有一个 yaml 文件,其中包含一个带有括号符号 {} 的字符串,与 python f 字符串配合使用,那么如何在此处利用 f 字符串插值?以这个简单的 yaml 文件为例:
# tmp.yaml
k1: val1
k2: val2 as well as {x}
Run Code Online (Sandbox Code Playgroud)
如果x = 'val3',我希望 k2 的值能够反映val2 as well as val3
# app.py
x = 'val3'
with open('tmp.yaml', 'rt') as f:
conf = yaml.safe_load(f)
print(conf)
{'k1': 'val1', 'k2': 'val2 as well as {x}'}
Run Code Online (Sandbox Code Playgroud)
这可以通过格式字符串很容易地完成......
print(conf['k2'].format(x=x))
val2 as well as val3
Run Code Online (Sandbox Code Playgroud)
但如何对 f 字符串执行同样的操作呢?
我发现这jinja2为这个问题提供了最简单的解决方案。
# tmp.yaml
k1: val1
k2: val2 as well as {{ x }}
Run Code Online (Sandbox Code Playgroud)
with open('tmp.yaml', 'rt') as f:
conf = f.read().rstrip()
print(conf)
# 'k1: val1\nk2: val2 as well as {{ x }}'
import jinja2
template = Template(conf)
conf = template.render(x='val3')
config = yaml.safe_load(conf)
print(config)
# {'k1': 'val1', 'k2': 'val2 as well as val3'}
Run Code Online (Sandbox Code Playgroud)