【问题标题】:Retrieve comments at the head of the document using ruamel.yaml使用 ruamel.yaml 检索文档头部的注释
【发布时间】:2021-06-23 11:34:05
【问题描述】:
是否有一种方法可以在加载后使用 ruamel.yaml 检索 YAML 文档头部的 cmets?
例如:
yaml_str = """\
# comment at head of document
date: 20210326 # comment about key-pair
"""
我知道如何检索date 的评论:
from ruamel.yaml import YAML
yml = YAML(typ='rt')
data = yml.load(yaml_str)
comments = data.ca.items.get('date')
或any other field in the document,但不是最初的 cmets。
【问题讨论】:
标签:
python
yaml
comments
ruamel.yaml
【解决方案1】:
目前没有获取此数据的方法。
开头找不到评论的原因,是因为
与所有其他 cmets 相比,处理方式不同。当在输入流中看到其他 cmets 时,
是可以附加评论的解析数据节点,但这当然不是
在任何数据之前的开头的评论的情况。
您可以检索这些 cmets,但您应该确保检查
ruamel.yaml 的版本,因为更改了 cmets 的附加方式have
been announced
import ruamel.yaml
yaml_str = """\
# comment at head of document
# another one after empty line
date: 20210326 # comment about key-pair
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
if ruamel.yaml.version_info <= (0, 17, 0):
comments = [x.value for x in data.ca.comment[1]]
else:
raise NotImplementedError
print(comments)
给出:
['# comment at head of document\n\n', '# another one after empty line\n']
.ca 的 .comment 属性在未来几乎肯定会消失
发布,所以你可以只使用try-except。并将空行的排序规则
前面的注释作为额外的换行符,格式也会发生变化,但会
最有可能在发生这种情况时获得稳定的访问方法(所以你应该
不必多次升级您的代码)。
【解决方案2】:
这就是我发现的检查对象的方式:
>>> data.ca.comment[1][0].value
'# comment at head of document\n'