【问题标题】:ruamel.yam is not preserving all commentsruamel.yam 没有保留所有评论
【发布时间】:2017-04-13 19:29:11
【问题描述】:

原始 YAML 文件是

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  gets: gut
  #comment5

在python中,我做到了

yml = ruamel.yaml.round_trip_load(yaml_input_str)
exec("del yml['toplevel']['gets']")
output_str = ruamel.yaml.round_trip_dump(yml)

output_str 变成

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment5

comment3 和comment4 消失。这是设计的还是错误的?

【问题讨论】:

  • 看看这个答案:stackoverflow.com/a/38252508/252648。看起来对 cme​​ts 的处理还没有完全完成。
  • @mangoDrunk ruamel.yaml 的往返模式的目的是能够加载 YAML 文件(例如用于配置),更改一些值并将文件写回而不会丢失厘米。您链接到的帖子的作者试图做的事情超出了其设计目的。在ruamel.yaml 中恰好有一些机制可以更容易地实现该目标,而不是从其他尚未完全完成 cmets 的 Python 包(即所有其他 Python 包)开始,包括不丢弃 cmets阅读时。

标签: ruamel.yaml


【解决方案1】:

这是设计的。但是,与 ruamel.yaml 一样,文档不足,主要是由于包作者的懒惰。

cmets 与键相关联,而不是与相对于映射开头的某个位置相关联。由于 YAML 被标记化的方式,cmets 与以下键相关联。 这样做的结果是,如果不再有键,注释仍然可用,但不再发出。

这样做的副作用是,如果你这样做:

import sys
import ruamel.yaml

yaml_str = """\
toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  gets: gut
  #comment5
"""

data = ruamel.yaml.round_trip_load(yaml_str)
del data['toplevel']['gets']
ruamel.yaml.round_trip_dump(data, sys.stdout)

你会得到你的output_str,然后如果你跟着它:

data['toplevel']['gets'] = 42
ruamel.yaml.round_trip_dump(data, sys.stdout)

你会得到:

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  gets: 42
  #comment5

因此 cmets “神奇地”重新出现。

如果您想将 cmets 移动到嵌套映射的末尾(使用键 'toplevel'),您可以这样做:

comment_tokens = data['toplevel'].ca.items['gets'][1]
del data['toplevel'].ca.items['gets']  # not strictly necessary
data['toplevel'].ca.end = comment_tokens

你会得到:

toplevel:
  #comment1
  hello: gut
  #comment2
  howdy: gut #horizontalcomment
  #comment3
  #comment4
  #comment5

这可能是您最初所期望的。


这让我想知道为什么你使用 exec() 而不是直接使用:

del yml['toplevel']['gets']

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2012-09-11
    • 1970-01-01
    • 2021-09-29
    • 2020-10-28
    • 2021-02-20
    • 2015-06-12
    • 1970-01-01
    • 2021-04-17
    相关资源
    最近更新 更多