【问题标题】:How to correctly output strings with ruamel.yaml如何使用 ruamel.yaml 正确输出字符串
【发布时间】:2021-09-21 14:39:14
【问题描述】:

我正在尝试使用 ruamel 来更新一些dependabot 文件。

Dependabot 要求时间是一个字符串。 The property '#/updates/0/schedule/time' of type integer did not match the following type: string

以下代码可以重现错误行为:

import ruamel.yaml, sys
test = "time: 09:00"
yaml = ruamel.yaml.YAML()
yaml.dump(test, sys.stdout)

给予:

'time: 09:00'

不应该是这样的吗?

'time: "09:00"'

【问题讨论】:

    标签: python ruamel.yaml


    【解决方案1】:

    输出是正确的 YAML。因为你转储了一个字符串和你的 字符串包括一个冒号(YAML 的值指示符),后跟一个空格,你会得到引号 您的输出,否则输入将作为字典读回。

    要获得 09:00 周围的引号,它们必须出现在您的输入字符串中:

    import ruamel.yaml, sys
    test = "time: \"09:00\""
    yaml.dump(test, sys.stdout)
    

    给出:

    'time: "09:00"'
    

    如果你不想要单个字符串作为输出,那么不要转储字符串,而是转储字典

    test = dict(time="09:00")
    yaml.dump(test, sys.stdout)
    

    给出:

    time: 09:00
    

    由于在这种情况下不需要在 09:00 周围加上引号,ruamel.yaml 不需要 把它们放在那里。你可以通过09:00(而不是time)强制它们 创建一个双引号字符串项,然后转储:

    DQ = ruamel.yaml.scalarstring.DoubleQuotedScalarString
    test = dict(time=DQ("09:00"))
    yaml.dump(test, sys.stdout)
    

    给出:

    time: "09:00"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多