PyYAML转储对象路径

时间:2012-10-09 06:35:05

标签: pyyaml

我在使用PyYAML转储和加载YAML文件时遇到问题。

我有两个独立的应用程序A和B.我想在A中转储一个YAML文件,然后加载它并在B中使用它。但是对象的路径似乎不正确。

A-folder
    dump.py
B-folder
    the_module.py
    use.py

在dump.py中,我的代码如下:

yaml.dump(the_class_instance, file_stream, default_flow_style=False)

它提供了一个YAML文件:

!!python/object:B-folder.the_module.the_class
attribute_0: !!python/long '10'
attribute_1: !!python/long '10'

然后我需要在use.py中使用这个YAML文件。但我无法正确加载它作为the_module.the_module.the_class的一个实例。它说:

cannot find module 'B-folder.the_module' (No module named B-folder.the_module)

我试图在另一个模块B-folder.adaptor中进行转储,在dump.py中它只调用B-folder.adaptor中的方法,但它仍然会给出相同的结果。

如何处理?感谢。

1 个答案:

答案 0 :(得分:1)

这里的问题实际上不是PyYAML,而是Python的模块加载。

在A中,我假设您将the_module作为B文件夹包的一部分导入,使用import B-folder.the_modulefrom B-folder import the_module。在这种情况下,模块名称为B-folder.the_module。如您所见,这将被放入YAML文件中。

在B中,我假设您只是在内部导入the_module,类似import the_module。在这种情况下,模块名称为the_module。这与B-folder.the_module不同,这就是您收到错误的原因。如果您使用from B-folder import the_moduleimport B-folder.the_module在B中导入,即使您位于同一文件夹中,也应该可以解决问题。

相关问题