yaml.safe_load 返回字符串而不是对象

Ale*_*ich 6 pyyaml python-3.x

我有这段代码:

    config_object = yaml.safe_load(config_string)
    print("passed config: {}".format(config_object)) 
    ^^ prints expected yaml structure

    print("deserialized config object type: {}".format(type(config_object)))
    ^^ prints deserialized config object type: <class 'str'>

    value = config_object["field1"]["field2"]["field3"]
    ^^  Error: string indices must be integers
Run Code Online (Sandbox Code Playgroud)

我的 yaml 配置:

   ---
   field1:
     field2:
       field3: value
     field4: value
   ...
Run Code Online (Sandbox Code Playgroud)

我不明白为什么返回字符串。我在这里没有看到任何字符串返回类型:https ://pyyaml.org/wiki/PyYAMLDocumentation

小智 6

我对不同的数据遇到了同样的问题:

train:images/train
Run Code Online (Sandbox Code Playgroud)

我通过在冒号后添加空格解决了这个问题:

train: images/train
Run Code Online (Sandbox Code Playgroud)


Bas*_*mer 5

技巧是将函数参数包装open()如下:

config_object = yaml.safe_load(open(config_string))
Run Code Online (Sandbox Code Playgroud)