get comment during iteration in ruamel.yaml(在 ruamel.yaml 迭代期间获取评论)
问题描述
我如何在遍历 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
and
not 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), but there is no guarantee it might not to change.
这篇关于在 ruamel.yaml 迭代期间获取评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 ruamel.yaml 迭代期间获取评论
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01