ruamel.yaml dump不保留布尔值大小写

时间:2017-09-01 13:27:35

标签: python ruamel.yaml

我有一个简单的python 2.7.12脚本在linux和osx上运行,提供相同的输出。在转储期间使用ruamel时,布尔值似乎转换为全部小写。作为测试,当字段转换为不带引号的字符串时,不存在大小写转换。

档案: test.yml

namespace: default
testapp_appname: testapp

images:
  testapp:
    path: "foo/testapp"
    tag: "202120810083053-1.2.3"

testapp_replicas: 1

testapp_monitoring_enabled: False
testapp_node_selector: ""

我的简单测试脚本:

import ruamel
import sys
from ruamel.yaml import YAML
yaml = YAML()


def main():
    config_path = "test.yml"
    image = "testapp"
    timestamp = "202120810083053-"
    version = "1.2.3"
    config = ruamel.yaml.round_trip_load(open(config_path), preserve_quotes=True)
    config['images'][image]['tag'] = "{}{}".format(timestamp, version)
    ruamel.yaml.round_trip_dump(config, sys.stdout)

if __name__ == "__main__":
    main()

输入:

testapp_monitoring_enabled: False

输出:

testapp_monitoring_enabled: false

1 个答案:

答案 0 :(得分:2)

您正在将新API(yaml = YAML())与旧API(ruamel.yaml.round_trip_dump())混合,这可能但不是必需的(也不推荐)。

ruamel.yaml不保留布尔值的大小(FalseFALSE),但可以使用boolean_representation属性设置转储中使用的值(当然会影响所有布尔人):

import sys
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
yaml.boolean_representation = ['False', 'True']

def main():
    config_path = "test.yml"
    image = "testapp"
    timestamp = "202120810083053-"
    version = "1.2.3"
    config = yaml.load(open(config_path))
    config['images'][image]['tag'] = "{}{}".format(timestamp, version)
    yaml.dump(config, sys.stdout)

if __name__ == "__main__":
    main()

会得到你:

namespace: default
testapp_appname: testapp

images:
  testapp:
    path: "foo/testapp"
    tag: "202120810083053-1.2.3"

testapp_replicas: 1

testapp_monitoring_enabled: False
testapp_node_selector: ""