在python中序列化自定义模块和对象

2024-06-01 01:22:51 发布

您现在位置:Python中文网/ 问答频道 /正文

问题

假设我有一个名为custom_module的模块:

class CustomClass:
    pass

我在一个脚本中使用这个类,该脚本序列化了我在custom_module中定义的类的对象:

^{pr2}$

我将这个pickle文件复制到另一个环境并用另一个脚本加载它:

^{3}$

这将产生以下错误:

Traceback (most recent call last):
  File "loader.py", line 4, in <module>
    custom_object = cloudpickle.load(file)
ModuleNotFoundError: No module named 'custom_module'

尴尬的解决方案

作为解决方法,可以读取并执行脚本中custom_module中的所有内容:

exec(open(path.join('custom_module.py')).read())

但这看起来很奇怪,我不能使用CustomClass作为cm.CustomClass。有没有其他解决方案不涉及将第一个环境中的所有代码复制到第二个环境中?在


Tags: 模块对象py脚本序列化定义环境custom