tikej
tikej

Reputation: 322

How do I fix EOFError when unpickling from a BytesIO object?

Is this possible to pickle and unpickle data without creating a file for it? In the question that was suggested as duplicate I don't see how to unpickle this.

Pickle.dump to variable

I want to do this remotely so I can't create new files on the fly. All examples with pickling and unpickling show use of pickle.dump, and pickle.load. I read the docs, and the file argument can be a BytesIO object but when I try to use load() function, I get.

EOFError: Ran out of input

Can somebody give me some examples of how to do this? What I currently have is:

a = A("some_random_string")
bio = BytesIO(b"some_bytes_data")
d = pickle.dump(a, bio)
f = pickle.Unpickler(bio).load()

The load gives me the above error. What am I doing wrong?

Upvotes: 2

Views: 1195

Answers (1)

tikej
tikej

Reputation: 322

I was able to resolve it after all. Using dumps instead of dump made it possible for me. An example of how it works in my case now:

from io import BytesIO
import pickle
a = b"asdf"
f = pickle.dumps(a)
file = BytesIO(f)
unpickled = pickle.load(file) # It is equal to initial value.

Maybe it helps someone else too.

Upvotes: 1

Related Questions