gpt4 book ai didi

python - ruamel.yaml 转储不保留 bool 值大小写

转载 作者:行者123 更新时间:2023-12-01 02:38:17 30 4
gpt4 key购买 nike

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

文件: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:假

输出:

testapp_monitoring_enabled: false

最佳答案

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

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

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

关于python - ruamel.yaml 转储不保留 bool 值大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001328/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com