如何防止 ruamel 在值中间换行?

How to prevent ruamel from breaking a line in the middle of a value?

我有两个问题!

  1. 有没有办法防止 round_trip_dump 或什至只是普通的转储在句子中间换行?每当我的 YAML 文件中有一个长句子(即描述),并且我使用脚本更改一些内容时,它会换行并破坏我的文件。

  2. 转储和round_trip_dump有什么区别?

这是我的代码:

import ruamel.yaml

yml = "test.yml"

data = ruamel.yaml.round_trip_load(open(yml, "r"), preserve_quotes=True)
ruamel.yaml.round_trip_dump(data, open(yml, "w"))

这是我当前的文件:

person_1:
  name: Michael
  age: 20
  description: A very cool person with some really cool text, to show this issue, how do I fix this, it's going to break a line in a few words

我想简单地加载和转储它(并修复缩进,但在这种情况下,它已经修复)。所以,当我 运行 我的代码时,我得到这个:

person_1:
   name: Michael
   age: 20
   description: A very cool person with some really cool text, to show this issue,
   how do I fix this, it's going to break a line in a few words

首先,您实际上无法获得您正在获得的输出。那实际上是无效的 YAML。 文件中以 spaces 和 how do I 开头的行将(必须)比 键 description。 其次,如果不指定不同的缩进,则无法在 ruamel.yaml.

中获得三个 space 缩进

所以输出不是来自您提供的程序,或者您犯了格式错误。

你得到的输出是:

person_1:
  name: Michael
  age: 20
  description: A very cool person with some really cool text, to show this issue,
    how do I fix this, it's going to break a line in a few words

这在语义上与您的输入相同。最后 (how do...) 行是从以下开始的普通标量的续行 A very cool。加载时不会有换行符,只有 issue,how 之间的 space。

你得到续行是因为你的内容更宽 比默认输出宽度,所以最简单的是增加它从 默认 "best width" 80.

我也确实建议使用新的 API(它已经变旧了),并遵循 文件扩展名 .yaml(这是自 2006 年 9 月以来推荐的扩展名)。

import sys
import ruamel.yaml

yaml_file = "test.yaml"

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=3, sequence=2, offset=0)  # sequence and offset have their default values here
yaml.preserve_quotes = True
yaml.width = 800    # this is the output line width after which wrapping occurs
with open(yaml_file) as fp:
    data = yaml.load(fp)
with open(yaml_file, 'w') as fp:
    yaml.dump(data, fp)

之后输出文件看起来像原始文件,但缩进了三个位置:

person_1:
   name: Michael
   age: 20
   description: A very cool person with some really cool text, to show this issue, how do I fix this, it's going to break a line in a few words

新API中的默认值是往返(即YAML(typ='rt')),如果你想要等效 旧函数 dump() (没有 Dumper 参数),你应该 使用 yaml = YAML(typ='unsafe')。倾倒本身并不安全,但 等效的旧式 load() 函数是。

rtunsafe 之间的差异(主要等于 round_trip_dumpdump) 的区别主要在于前者 知道往返装载机的所有特殊事物 蜜饯:

  • 风格
  • 评论
  • anchor/alias 名字
  • 整数"style"(八进制、二进制、十六进制、前导零)
  • 浮动 "style"(科学记数法)
  • 可选:标量周围的引号
  • 转储从 YAML 加载的标记对象(没有注册特殊定义)

unsafe/normal 转储知道如何转储大多数 Python 对象,而 如果您使用往返(或 safe) 自卸车。

您不应该尝试使用不安全的转储程序转储您加载的内容 与往返装载机。

yaml_i = ruamel.yaml.YAML()
yaml_o = ruamel.yaml.YAML(typ='unsafe')
with open(yaml_file) as fp:
    data = yaml_i.load(fp)
with open(yaml_file, 'w') as fp:
    yaml_o.dump(data, fp)

它可能会工作,但输出是 "unreadable"(评论等将丢失)。另一种方式 有效,但当然不推荐。