PyYaml.load_all()返回生成器而不是dict?

时间:2017-03-15 05:56:02

标签: python dictionary yaml

我第一次使用Yaml(和Python!)。我试图从单个.yaml文件中加载多个文档,但没有得到我期望的结果。我期待一个包含每个文档的词典,但是我得到了一个生成器对象......?我应该注意,当我在单个文档yaml文件中的先前测试(而不是load_all())中使用yaml.load()时,我能够很好地获得字典。

我错过了哪些明显的事情阻止我接收多个文档?

测试yaml:

---
Tiles:
 dungeon_floor:
   name: 'Dungeon Floor'
   blocked: False
   block_sight: False
   terrain_type: CONST.E_TERRAIN_TYPES.FLAT_FLOOR
   persistent_effects: 'None'
...
---
NPCs:
 gnoll:
   name: "Gnoll"
   equipment: Sword, Shield

def yaml_loader(filepath):
    """Load a yaml file."""
    with open(filepath, "r") as file_descriptor:
        data = yaml.load_all(file_descriptor)
    return data

试图加载和打印字典的代码:

def yaml_loader(filepath):
    """Load a yaml file."""
    with open(filepath, "r") as file_descriptor:
        data = yaml.load_all(file_descriptor)
    return data

if __name__ == "__main__":
    filepath = CONST.YAML_ECS_CONFIG_PATH
    data = yaml_loader(filepath)
    print(data)

...产生以下终端输出:

<generator object load_all at 0x0000000003A64990>

Process finished with exit code 0

1 个答案:

答案 0 :(得分:7)

好吧,看load_all implementation就会明白为什么会发生这种情况:

def load_all(stream, Loader=Loader):
    """
    Parse all YAML documents in a stream
    and produce corresponding Python objects.
    """
    loader = Loader(stream)
    try:
        while loader.check_data():
            yield loader.get_data()
    finally:
        loader.dispose()

它确实是一个发电机。所以你只需要将它转换为一个列表:

 data = list(yaml.load_all(file_descriptor))