在 ruamel.yaml 迭代期间获取评论

时间:2023-04-16
本文介绍了在 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 1the 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 迭代期间获取评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:大多数自定义 python 对象的新 PyYAML 版本中断 - RepresenterError 下一篇:使用 yamltodb 将 YAML 数据转换为数据框

相关文章