Python pickle: ImportError: No module named __main__

Python pickle: ImportError: No module named __main__

您好,我有 2 个非常简单的程序正在 运行 两台计算机上运行。哪个 pickle 和 unpickle a class.

在一台计算机上(使用 Linux):

import cPickle

# Define class
class test():
    def __init__():
        self.foo = 1

# Initialise and pickle class
bar = test()
with open("test.pkl", "wb") as file_:
    cPickle.dump(bar, file_, protocol=0)

在第二台电脑上(使用Windows):

import cPickle

# Define class again
class test():
    def __init__():
        self.foo = 1 

# Unpickle file
with open("test.pkl", "rb") as file_:
    bar = cPickle.dump(file_)

但是我得到一个错误:

ImportError: No module named __main__

一台机器使用 windows,另一台机器使用 Linux,脚本和 pickle 正在使用 GIT(版本控制系统)传输。我不明白为什么会发生这种情况,因为 class 是直接在两个脚本的主体中定义的。

问题是由于换行造成的。当您签入文件时,通常 GIT 会自动将行结尾从 Windows 转换为 Linux 格式。但是,使用默认配置它不会对 pickle 文件执行此操作,因此当您阅读时它在 Windows 机器上无法正确识别行尾。

一旦您将行结尾转换为适合 OS 的格式,pickle 将正确加载。

我不确定为什么 Python 将 "ImportError: No module named __main__" 报告为错误,因为这非常令人困惑。