我正在编辑一个很大的 yaml 配置文件。这是理想的格式。
...
- name: apple
Formula: |-
x = 3 + 4;
apple = x * 3 + y;
Inputs:
- y
- name: banana
Formula: |-
x = 8 + 4;
apple = x * 3 + y;
Inputs:
- y
...
使用 github 操作和问题模板,我可以自动添加新项目。假设用户想要使用 github 问题模板添加上面的
apple
。 python 脚本输出这个(如下),但它不是我理想的格式。我的问题是如何解决这个问题。
- name: apple
Formula: "x = 3 + 4;\n\rapple = x * 3 + y;"
Inputs:
- y
我有一个可以加载和编辑的模板 yaml 文件。字符串上的 print 语句将换行符输出为换行符。所以它不是一个原始字符串。相关的python代码:
import json
from ruamel.yaml import YAML
template[0]["Formula"] = newparam["Formula"] # newparam is the dict from the jsonload
targetyaml.append(template[0])
yaml = YAML()
yaml.default_flow_style = False
with open(afile, "w") as outfile:
yaml.dump(targetyaml, outfile)
注意:已经具有良好格式的列表项的往返将被保留。只是这个添加的参数没有按照我想要的方式格式化。
我尝试以几种方式用字符串替换换行符,以使转储按字面解释换行符。
如果您坚持按照自己想要的方式生成 YAML,有两件事要做:
从往返开始:
import sys
import ruamel.yaml
yaml_str = """\
- name: apple
Formula: |-
x = 3 + 4;
apple = x * 3 + y;
Inputs:
- y
"""
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
给出:
- name: apple
Formula: |-
x = 3 + 4;
apple = x * 3 + y;
Inputs:
- y
因此保留了经过 chomped 的文字标量(您已经从文档的其他部分知道了这一点)。现在检查该标量是如何加载的:
lit = data[0]['Formula']
print('inspecting:', repr(lit), 'type:', type(lit))
打印:
inspecting: 'x = 3 + 4;\napple = x * 3 + y;' type: <class 'ruamel.yaml.scalarstring.LiteralScalarString'>
使用该类型:
from ruamel.yaml.scalarstring import LiteralScalarString as LSS
data = [dict(name='apple', Formula=LSS('x = 8 + 4\naple = x * 3 + y;'), Inputs=['y'])]
yaml.dump(data, sys.stdout)
给出:
- name: apple
Formula: |-
x = 8 + 4
aple = x * 3 + y;
Inputs:
- y
是否(以及哪个)获得复合指示符取决于您传递的字符串有多少换行符 至
LSS
/LiteralScalarString
。如果没有换行符,您将获得剥离咀嚼指示器 (-
)。