酸洗用importlib.util导入的对象 [英] Pickling objects imported with importlib.util

查看:101
本文介绍了酸洗用importlib.util导入的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python的泡菜时遇到问题.我需要通过给它们提供指向importlib.util的文件路径来加载一些Python模块,如下所示:

I ran into a problem while using Python's pickle. I need to load some Python modules by giving their file paths to importlib.util, like so:

import importlib.util
spec = importlib.util.spec_from_file_location('custom', 'C:\path\to\.py\file.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

我想实例化已加载模块中的一些对象,并对其进行序列化以供以后使用,但是当我尝试使用时:

I would like to instantiate some objects from the loaded module and serialize them for later use, but when I try:

pickle.dump(module.ObjectFromModule(), open('C:\object\location\obj.p', 'wb'))

我明白了: _pickle.PicklingError:无法腌制:导入模块自定义"失败

I get this: _pickle.PicklingError: Can't pickle : import of module 'custom' failed

如果我尝试腌制通过import语句导入的对象,则不会发生.我该如何绕过呢?

If I try pickling the object that is imported via the import statement, this doesn't happen. How can I bypass this?

推荐答案

使其工作最简单的方法是通过以下方式将模块手动添加到sys.module中:

The easiest way to make it working is to manually add the module to the sys.module the following way:

import importlib.util
import sys

spec = importlib.util.spec_from_file_location('custom', 'C:\path\to\.py\file.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules['custom'] = module

这篇关于酸洗用importlib.util导入的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆