6

问题

假设我有这个模块名为custom_module

class CustomClass:
    pass

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

import cloudpickle
import custom_module as cm

custom_object = cm.CustomClass()
with open('filename.pkl', 'wb') as file:
    cloudpickle.dump(custom_object, file)

我将此泡菜文件复制到另一个环境并使用另一个脚本加载它:

import cloudpickle

with open('filename.pkl', 'rb') as file:
    custom_object = cloudpickle.load(file)

这会产生这个错误:

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. 是否有任何其他解决方案不涉及将第一个环境中的所有代码复制到第二个环境?

4

0 回答 0