这就是我想要做的(代码在Python 3):是否可以在跨文档的多文档YAML流中使用别名?
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)
你应该使用'safe_load_all()'和'safe_load()'除非你在真正的文件已标记YAML内容。这不会解决找不到锚的问题,但它会阻止潜在的恶意YAML在您的程序中执行任意代码 – Anthon