繁体   English   中英

如何使用ruamel.yaml在Python中向YAML插入注释行?

[英]How to insert a comment line to YAML in Python using ruamel.yaml?

我有一个这样的结构,我想使用ruamel.yaml在其中添加注释行:

xyz:
  a: 1    # comment 1
  b: 2

test1:
  test2:
    test3: 3

现在,我想插入注释行(不是eol_comments),使其看起来像这样:

xyz:
  a: 1    # comment 1
  b: 2

# before test1 (top level)
test1:
  # before test2
  test2:
    # after test2
    test3: 3

我知道,我可以使用ruamel.yaml添加eol_comments,但是我没有找到添加整个注释行的方法。

确实在ruamel.yaml<=0.12.18没有函数可以在键之前的行上插入注释,但是有一个函数可以在结构开头设置注释: .yaml_set_start_comment 这样,您就可以设置要添加的三个注释中的两个:

import sys
import ruamel.yaml

yaml_str = """\
xyz:
  a: 1    # comment 1
  b: 2

test1:
  test2:
    test3: 3
"""

data = ruamel.yaml.round_trip_load(yaml_str)
data['test1'].yaml_set_start_comment('before test2', indent=2)
data['test1']['test2'].yaml_set_start_comment('after test2', indent=4)
ruamel.yaml.round_trip_dump(data, sys.stdout)

给出:

xyz:
  a: 1    # comment 1
  b: 2

test1:
  # before test2
  test2:
    # after test2
    test3: 3

实际上, xyztest1的值之间有一条空行构成的“注释”,但是如果将注释附加到该结构,然后在test1之前插入新的键,则不会显示您想要的内容。 因此,要做的是在键test1之前显式插入注释。 您可以往返加载预期的输出,以查看内部Comment外观:

yaml_str_out = """\
xyz:
  a: 1    # comment 1
  b: 2

# before test1 (top level)
test1:
  # before test2
  test2:
    # before test3
    test3: 3
"""
test = ruamel.yaml.round_trip_load(yaml_str_out)
print(test.ca)

提供(将其包装起来以便于查看):

Comment(comment=None,
        items={'test1': [None, 
                        [CommentToken(value='# before test1 (top level)\n')], 
                        None, 
                        [CommentToken(value='# before test2\n')]]})

如您所见# before test2被视为键之后的注释。 并且执行test['test1'].yaml_set_start_comment('xxxxx', indent=2)不会产生任何效果,因为与test1相关联的注释会否决# xxxxx 不会显示在转储中。

有了这些信息和一些背景知识,我改编了yaml_set_start_comment()一些代码(假设原始导入和yaml_str ):

def yscbak(self, key, before=None, indent=0, after=None, after_indent=None):
    """
    expects comment (before/after) to be without `#` and possible have multiple lines
    """
    from ruamel.yaml.error import Mark
    from ruamel.yaml.tokens import CommentToken

    def comment_token(s, mark):
        # handle empty lines as having no comment
        return CommentToken(('# ' if s else '') + s + '\n', mark, None)

    if after_indent is None:
        after_indent = indent + 2
    if before and before[-1] == '\n':
        before = before[:-1]  # strip final newline if there
    if after and after[-1] == '\n':
        after = after[:-1]  # strip final newline if there
    start_mark = Mark(None, None, None, indent, None, None)
    c = self.ca.items.setdefault(key, [None, [], None, None])
    if before:
        for com in before.split('\n'):
            c[1].append(comment_token(com, start_mark))
    if after:
        start_mark = Mark(None, None, None, after_indent, None, None)
        if c[3] is None:
            c[3] = []
        for com in after.split('\n'):
            c[3].append(comment_token(com, start_mark))

if not hasattr(ruamel.yaml.comments.CommentedMap, 
               'yaml_set_comment_before_after_key'):
    ruamel.yaml.comments.CommentedMap.yaml_set_comment_before_after_key = yscbak


data = ruamel.yaml.round_trip_load(yaml_str)
data.yaml_set_comment_before_after_key('test1', 'before test1 (top level)',
                                       after='before test2', after_indent=2)
data['test1']['test2'].yaml_set_start_comment('after test2', indent=4)
ruamel.yaml.round_trip_dump(data, sys.stdout)

并得到:

xyz:
  a: 1    # comment 1
  b: 2

# before test1 (top level)
test1:
  # before test2
  test2:
    # after test2
    test3: 3

hasattr的测试是确保将其添加到ruamel.yaml不会覆盖该函数。

顺便说一句:所有评论都是YAML中的行尾评论,其中一些评论之前可能只有有效的YAML。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM