这就是我想要做的(代码在 Python 3 中):
import ruamel.yaml as yaml
from print import pprint
yaml_document_with_aliases = """
title: test
choices: &C
a: one
b: two
c: three
---
title: test 2
choices: *C
"""
items = list(yaml.load_all(yaml_document_with_aliases))
结果是:
ComposerError: found undefined alias 'C'
当我使用非基于文档的 YAML 文件时,这可以按预期工作:
import ruamel.yaml as yaml
from print import pprint
yaml_nodes_with_aliases = """
-
title: test
choices: &C
a: one
b: two
c: three
-
title: test 2
choices: *C
"""
items = yaml.load(yaml_nodes_with_aliases)
pprint(items)
结果:
[{'choices': {'a': 'one', 'b': 'two', 'c': 'three'}, 'title': 'test'},
{'choices': {'a': 'one', 'b': 'two', 'c': 'three'}, 'title': 'test 2'}]
(无论如何我想完成的事情)
由于现在不可能,我正在使用以下脆弱的解决方法:
def yaml_load_all_with_aliases(yaml_text):
if not yaml_text.startswith('---'):
yaml_text = '---\n' + yaml_text
for pat, repl in [('^', ' '), ('^\s*---\s*$', '-'), ('^\s+\.{3}$\n', '')]:
yaml_text = re.sub(pat, repl, yaml_text, flags=re.MULTILINE)
yaml_text = yaml_text.strip()
return yaml.safe_load(yaml_text)