如何使用 ruamel.yaml 读取多个 yaml 定义

How to read multiple yaml definitions with ruamel.yaml

是否可以从单个文件中读取多个 yaml 定义?

示例代码:

import ruamel.yaml

text = '''
---
foo: bar
---
baz: baz
...
'''

yaml = ruamel.yaml.YAML(typ='rt')
yamlFile = yaml.load(text)

预期的行为类似于:

for i in yamlFile:
  print(i) #foo: bar, baz: baz

实际行为是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/bruno.miranda/Desktop/iac/iac-wrapper/venv/lib/python3.9/site-packages/ruamel/yaml/main.py", line 434, in load
    return constructor.get_single_data()
  File "/Users/bruno.miranda/Desktop/iac/iac-wrapper/venv/lib/python3.9/site-packages/ruamel/yaml/constructor.py", line 120, in get_single_data
    node = self.composer.get_single_node()
  File "/Users/bruno.miranda/Desktop/iac/iac-wrapper/venv/lib/python3.9/site-packages/ruamel/yaml/composer.py", line 81, in get_single_node
    raise ComposerError(
ruamel.yaml.composer.ComposerError: expected a single document in the stream
  in "<unicode string>", line 3, column 1:
    foo: bar
    ^ (line: 3)
but found another document
  in "<unicode string>", line 4, column 1:
    ---

也尝试在构造函数上不使用 typ='rt',但我得到了相同的结果。

我使用的版本是:

pip show ruamel.yaml
Name: ruamel.yaml
Version: 0.17.16

除了 .load() 之外,还有 .load_all() 为所有加载的数据提供一个迭代器,每个文档一个。

yaml = ruamel.yaml.YAML()
for data in yaml.load_all():
    do_your_thing_with(data)