简体   繁体   中英

Python pickle: ImportError: No module named __main__

Hi I have a 2 very simple programs that are being run on two computers. Which pickle and unpickle a class.

On one computer (using 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)

On the second computer (using 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_)

But I get an error:

ImportError: No module named __main__

One machine is using windows, another is using Linux and the script and pickle are being transferred using GIT (version control system). I cant understand why this is occurring as the class is defined directly in the main in both scripts.

The problem is due to line endings. Usually GIT automatically converts line endings from Windows to Linux format when you check the files in. However, using the default configuration it dosn't do this for pickle files and therefore when you read it on the Windows machine it dosn't recognise the line endings properly.

Once you convert the line endings to the approiate format for the OS the pickle will load properly.

Im not sure why Python reports "ImportError: No module named __main__ " as the error as this is very confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM