问题描述
我如何在遍历 YAML 对象时获取注释
How can I get the comments when I iterate through the YAML object
yaml = YAML()
with open(path, 'r') as f:
yaml_data = yaml.load(f)
for obj in yaml_data:
# how to get the comments here?
这是源数据(ansible playbook)
This is the source data (an ansible playbook)
---
- name: gather all complex custom facts using the custom module
hosts: switches
gather_facts: False
connection: local
tasks:
# There is a bug in ansible 2.4.1 which prevents it loading
# playbook/group_vars
- name: ensure we're running a known working version
assert:
that:
- 'ansible_version.major == 2'
- 'ansible_version.minor == 4'
在Anthon评论后,这是我发现访问子节点中评论的方式(需要细化):
After Anthon comments, this is the way I found to access the comments in the child nodes (needs to be refined):
for idx, obj in enumerate(yaml_data):
for i, item in enumerate(obj.items()):
pprint(yaml_data[i].ca.items)
推荐答案
你没有指定你的输入,但是因为你的代码需要一个 obj
并且不是键,我假设您的 YAML 的根级别是序列而不是映射.如果您想在每个元素(即 nr 1
和 the last
)之后获得注释,您可以这样做:
You did not specify your input, but since your code expects an obj
andnot a key, I assume the root level of your YAML is a sequence and not mapping.If you want to get the comments after each element (i.e nr 1
and the last
) you can do:
import ruamel.yaml
yaml_str = """
- one # nr 1
- two
- three # the last
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
for idx, obj in enumerate(data):
comment_token = data.ca.items.get(idx)
if comment_token is None:
continue
print(repr(comment_token[0].value))
给出:
'# nr 1
'
'# the last
'
您可能想要去掉前导八字和尾随换行符.
You might want to strip of the leading octothorpe and trailing newline.
请注意,这适用于当前版本 (0.15.61),但是不能保证它不会改变.
Please note that this works with the current version (0.15.61), butthere is no guarantee it might not to change.
这篇关于在 ruamel.yaml 迭代期间获取评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!