1

I have a Python program that is parsing a number of YAML files, some containing comments, anchors, references, and merge keys that I'd like preserved when I load the YAML file into my parser. ruamel.yaml seems to have round-trip preservation of these when I run the following:

with open(yaml_file, "r") as f:
    yaml = f.read()
parsed_yaml = ruamel.yaml.load(yaml, ruamel.yaml.RoundTripLoader)
print ruamel.yaml.dump(parsed_yaml,Dumper=ruamel.yaml.RoundTripDumper)

Which prints out the original file yaml_file as it was presented including comments and merge keys. I'm wondering if I can access these comments and other keys while the YAML is parsed in OrderedDict form. I need to convert these YAML files to an intermediate type, so being able to both get and set comments, merge keys, anchors, and references is a high priority.

4

1 回答 1

2

是的,您可以访问评论等。您的映射(python )dict将被加载到. 这些分别是and的子类。和。_CommentedMaplistCommentedSeqordereddictCommentedBaselistCommentedBase

CommentedBase有几个属性,注释、合并、锚点和流式信息附加到这些属性上。它还有几种方法可以设置/获取这些值,这些值依赖于一些地图/序列特定的辅助函数。

import sys
from ruamel.yaml import YAML

yaml_str = """\
a: 1   # comment 1
b: 2
c: 3
d: 4
e: 5
"""

yaml = YAML()
data = yaml.load(yaml_str)
data.yaml_add_eol_comment('comment 2', key='c')
data.yaml_add_eol_comment('#  comment 3', key='e', column=8)
yaml.dump(data, sys.stdout)

会给你:

a: 1   # comment 1
b: 2
c: 3   # comment 2
d: 4
e: 5    #  comment 3

请注意:

  • 如果您不指定起始列,则采用下一个先前评论的列。
  • #如果注释字符串尚未以该字符组合开头,则将插入前导和空格。
  • 标量和注释之间至少有一个空格。

该接口的文档不足,主要是因为库作者的懒惰。您最好查看评论测试锚点测试以获取一些示例。该界面还需要在属性内容级别上进行一些更改,例如允许将 EOL 注释附加到键以及键+值组合。以下 YAML 不会像您期望的那样/正确地往返:

abc:      # this is the key
    9989  # this is the value

因此,请务必包装您需要的功能,以便在接口以ruamel.yaml向后不兼容的方式更改时可以在其中进行更改。

于 2016-03-25T18:57:29.873 回答