【发布时间】:2017-04-03 18:35:21
【问题描述】:
这就是我想要做的(代码在 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)
【问题讨论】:
-
您应该使用
safe_load_all()和safe_load(),除非您在真实文件中标记了 YAML 内容。这并不能解决找不到锚点的问题,但可以防止潜在的恶意 YAML 在您的程序中执行任意代码
标签: python yaml ruamel.yaml