且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ruamel.yaml中的list元素中添加评论

更新时间:2023-11-30 13:20:40

与其在您的问题中写下您将要欣赏的内容,不如说是有用的 查看程序,确定做错了什么.

Instead of writing in your question what you would appreciate, it would have been more useful to see your program, to determine what you were doing wrong.

由于混合使用缩进样式,因此无法获得准确的缩进 想要一次转储.

Because you mix and match indentation styles, you cannot get the exact indentation you want in one dump.

import sys
import ruamel.yaml
CS = ruamel.yaml.comments.CommentedSeq  # defaults to block style
CM = ruamel.yaml.comments.CommentedMap  # defaults to block style

def FS(x):  # flow style list
   res = CS(x)
   res.fa.set_flow_style()
   return res


yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)

lst = CS()
lst.append(FS(['a', 'b', 'c']))
lst.append(FS(['d', 'e']))
lst.yaml_add_eol_comment("first list", 0, 0)
lst.yaml_add_eol_comment("second list\n\n", 1)
data = CM(flow_style_example=lst)

lst = CS()
data['block_style_example'] = lst
lst.append(CS(['a', 'b', 'c']))
lst[0].yaml_add_eol_comment("first list side comment", 0, 0)
lst.append(CS(['d', 'e']))
lst.yaml_set_comment_before_after_key(1, "second list top comment", 2)

lst = CS(['a', 'b'])
lst.yaml_add_eol_comment("foo", 0, 0)
lst.yaml_add_eol_comment("bar\n\n", 1)
data["list_of_elements_side_comment"] = lst
data.yaml_set_comment_before_after_key("list_of_elements_side_comment", "\n")

lst = CS(['a', 'b'])
lst.yaml_set_comment_before_after_key(0, "comment 1", 2)
lst.yaml_set_comment_before_after_key(1, "comment 2", 2)
data["list_of_elements_top_comment"] = lst


yaml.dump(data, sys.stdout)

给出:

flow_style_example:
  - [a, b, c] # first list
  - [d, e] # second list

block_style_example:
  -   - a # first list side comment
      - b
      - c
  # second list top comment
  -   - d
      - e

list_of_elements_side_comment:
  - a # foo
  - b # bar

list_of_elements_top_comment:
  # comment 1
  - a
  # comment 2
  - b

CommentedSeq的注释处理与 CommentedMap:注释当前存储为字典,其中 序列索引执行与映射键相同的功能,因此 在序列/列表上使用yaml_set_comment_before_after_key.

The comment handling for CommentedSeq is very similar to that of CommentedMap: comments are currently stored as a dict where the sequence index fulfills the same function as the mapping key, hence the use of yaml_set_comment_before_after_key on a sequence/list.

上面使用的是ruamel.yaml的内部结构,如果没有 通知CQ.有通知,但没有引起您的注意.因此(准备 来修复您安装的ruamel.yaml的版本号.

The above uses internals of ruamel.yaml, which might change without notice cq. with notice, but without you noticing. Therefore (be prepared to) fix the version number of ruamel.yaml you install.