-6

yaml 标记中有一个文件

 a:
  b:x
  test2
  test
  test3

如何使用python(2.7.x)和PyYAML获取x?

4

1 回答 1

2

You can't! The YAML you posted results in a dict containing just a single key, a which maps to the value "b:x test2 test test3" - you can easily test that by pasting your YAML here.

The reason for this is that you cannot mix key: value pairs and keyless items (like there would be in an array).

However, let's assume that you have proper YAML that contains an object a containing another object that maps b to x. For example this:

a:
    b: x
    c: test2
    d: test
    e: test3

In this case you'd use foo['a']['b'] to access x with foo being the object returned by your YAML parser.

The python code to get foo could look like this:

import yaml
with open('yourfile.yaml') as f:
    foo = yaml.safe_load(f)

I'm using safe_load since you most likely do not intend to create arbitrary Python objects from your YAML document and thus you want to use a function that cannot open a security hole if ever passed a malicious YAML document.

于 2013-02-10T12:34:11.797 回答