【问题标题】:pyYAML, expected NodeEvent, but got DocumentEndEventpyYAML,预期 NodeEvent,但得到 DocumentEndEvent
【发布时间】:2017-07-25 12:49:14
【问题描述】:

我正在尝试转储一个自定义对象,它是一种对象列表。所以我覆盖了YAMLOBject 类的to_yaml 方法,我将我的类设置为继承自:

@classmethod
def to_yaml(cls, dumper, data):
    """ This methods defines how to save this class to a yml
    file """

    passage_list = []

    for passage in data:
        passage_dict = {
            'satellite': passage.satellite.name,
            'ground_station': passage.ground_station.name,
            'aos': passage.aos,
            'los': passage.los,
            'tca': passage.tca,

        }
        passage_list.append(passage_dict)

    passage_list_dict = {
        'passages': passage_list
    }

    return dumper.represent(passage_list_dict)

当我调用yaml.dump 方法时,使用正确的数据正确创建了输出文件:

if save_to_file:
    with open(save_to_file, 'w') as f:
        yaml.dump(all_passages, f, default_flow_style=False)

但在执行结束时我得到一个EmitterError: expected NodeEvent, but got DocumentEndEvent()

我认为这与未正确关闭 YAML 文档有关,因为当我调试代码时,我得到了 save_to_file 文件,这些文件在文档末尾缺少新行。可以吗?或者是别的什么?

【问题讨论】:

  • 如果我使用dumper.represent_mapping(cls.yaml_tag, passage_list_dict) 它可以工作(但它会在文件顶部添加我想避免的标签)。

标签: python yaml pyyaml


【解决方案1】:

您的代码不起作用,因为dumper.represent 没有返回任何内容。您想改用dumper.represent_data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-05
    • 2022-08-12
    • 2021-12-20
    • 2020-01-16
    • 1970-01-01
    • 2021-08-20
    • 2020-11-07
    • 2020-08-05
    相关资源
    最近更新 更多