将 yaml 转储到变量,而不是使用 ruamel.yaml 将其流式传输到 stdout 中

dump the yaml to a variable instead of streaming it in stdout using ruamel.yaml

我找不到将 YAML 转储到 ruamel.yaml 中的变量的方法。使用 PyYAML,我可以实现如下相同的效果:

with open('oldPipeline.yml','r') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

a = yaml.dump(data)

但是当我尝试使用 ruamel.yaml 时,它会抛出异常 TypeError: Need a stream argument when not dumping from context manager

该错误清楚地表明您应该提供流,因此您应该这样做:

import io
import ruamel.yaml

yaml_str = b"""\
fact: The recommended YAML file extension has been .yaml since September 2006
origin: yaml.org FAQ
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
buf = io.BytesIO()
yaml.dump(data, buf)
assert buf.getvalue() == yaml_str

没有断言错误。

ruamel.yaml 和 PyYAML 使用流接口并将其写入缓冲区是 很少需要,应该避免,因为它效率低下,尤其是 在常见的 PyYAML 形式中:

print(yaml.dump(data))  # inefficient wrt time and space

而不是更合适

yaml.dump(data, sys.stdout)

Post-输出的处理最好在流中完成,例如 对象,或使用 基本中描述的 transform 选项 用法 文档部分。

进一步解释 here,当然你也可以 查看 PyYAML 是如何做到这一点的。