简体   繁体   中英

ruamel.yaml dump doesn't preserve boolean value case

I have a simple python 2.7.12 script running on both linux and osx providing the same output. When using ruamel during the dump, the value of a boolean seems to convert to all lowercase. As a test when the field is converted to an unquoted string there is no case conversion.

File: 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: ""

My simple test script:

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()

Input:

testapp_monitoring_enabled: False

Output:

testapp_monitoring_enabled: false

You are mixing the new API ( yaml = YAML() ) with the old API ( ruamel.yaml.round_trip_dump() ), that is possible but not necessary (nor recommended).

ruamel.yaml doesn't preserve the casing of your booleans ( False , FALSE ), but it is possible to set the values used in the dump using the boolean_representation attribute (this of course affects all booleans):

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()

will get you:

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: ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM