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 迭代期间获取评论


基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01