我正在从数据构建一个yaml文件,并向需要手动用户编辑的部分添加注释。对于每个数据类别,我都包含一个顶级注释,但我还希望在列表项上包含行尾 (eol( 注释。尝试此操作时,我遇到了 ruamel 代码内部的错误。
我正在使用ruamel.yaml 0.15.96。这是错误:
AttributeError: 'NoneType' object has no attribute 'append'
它出现在comments.py
,第261行,在yaml_set_comment_before_after_key
。
我认为因为我正在设置 eol 注释,数据结构不同,所以当我添加 before 注释时,此行执行:c[1].append(comment_token(com, start_mark))
并且失败了,因为c[1]
是None
而不是[]
.
# Pseudocode, removed irrelevant details
data = CommentedMap(TopLevelData)
data.yaml_set_start_comment(TOP_LEVEL_COMMENT)
temp_list = CommentedSeq()
for top_comment, start_index, matches in match_categories:
components = self._matches_to_components(matches)
for idx, subcomponent in enumerate(components):
temp_list.append(data)
temp_list.yaml_add_eol_comment(comment=inline_comment,
key=idx)
temp_list.yaml_set_comment_before_after_key(key=start_index,
before=top_comment,
indent=OFFSET)
data['subcomponents'] = temp_list
我希望输出看起来像这样:
# TOP_LEVEL_COMMENT
name: hydrated-cluster
subcomponents:
# top_comment
- data: elasticsearch-fluentd-kibana # inline comment
你的伪代码隐藏了你做错了什么。如果你愿意花时间做一个最小的非工作示例,生成该错误,您会注意到它会正常工作。由此,您可以返回以确定错误在代码中的位置。
使用与您使用的相同类和方法:
import sys
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap, CommentedSeq
data = CommentedMap(dict(name="hydrated-cluster"))
data.yaml_set_start_comment("TOP_LEVEL_COMMENT")
temp_list = CommentedSeq()
d2 = CommentedMap(data="elasticsearch-fluentd-kibana")
d2.yaml_add_eol_comment(comment="# inline comment", key='data')
data['subcomponents'] = l3 = CommentedSeq([d2])
l3.yaml_set_comment_before_after_key(key=0, before="top comment", indent=2)
yaml = ruamel.yaml.YAML()
yaml.indent(sequence=4, offset=2)
yaml.dump(data, sys.stdout)
以上给出了您的期望:
# TOP_LEVEL_COMMENT
name: hydrated-cluster
subcomponents:
# top comment
- data: elasticsearch-fluentd-kibana # inline comment