[英]How to avoid an error when applying comments eol and before a key to yaml using ruamel.yaml?
我正在根据数据构造一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.