Darina
Darina

Reputation: 1632

ImportError with cPickle

I've looked through the various replies to related cPickle questions, but none seem to help. Neither does using cloudpickle instead of cPickle.

I have a module named MyModule that defines a class MyClass

First, I run a script in a different folder from my project folder. I import my own class MyClass from the project, make an instance of the class and pickle it at target path.

sys.path.append(os.path.join(os.environ.get("PROJECT_ROOT"), 'src/'))
from MyModule import MyClass
class_instance = MyClass()
with gzip.open(os.path.join(target_path, 'net.p.gz'), "wb") as f:
    cPickle.dump(class_instance, f)

Then, in my main project, I want to load the pickled file

from MyModule import MyClass
with gzip.open(os.path.join(os.environ['PROJECT_ROOT'], 'resources/net.p.gz'), 'rb') as f:
        class_instance = cPickle.load(f)

This results in an

ImportError: No module named MyModule

However

test_instance = MyClass()
print (test_instance)

in the same file prints

<MyModule.MyClass object at 0x7fad03e3ead0>

So the module is obviously there and being improted.

Both times I am referring to the same module, it does not change location. What am I missing?

Upvotes: 1

Views: 744

Answers (1)

gplayer
gplayer

Reputation: 1811

Let's say you have MyModule here: ~/work/repo/my_module.py. If you want from MyModule import MyClass to work, then you have to have this on the python path: ~/work/repo. Try to do a import sys; print sys.path and check it out.

Upvotes: 1

Related Questions