如何取消腌制字节数据?

How can pickled byte data be unpickled?

如何从 BytesIO 对象写入和读回 pickled 数据?

我试过了:

import io
import cPickle as pickle

s1 = "foo"
bytes_io = io.BytesIO()
pickle.dump(s1, bytes_io, pickle.HIGHEST_PROTOCOL)
s2 = pickle.load(bytes_io)

pickle.load 行:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
EOFError

您只是没有倒回缓冲区:bytes_io.seek(0)pickle.load.

之前

可能您不想倒回到缓冲区的前面,而只是想倒回到已腌制数据的开头。然后在 pickling 之前用 bytes_io.tell() 读出流位置并寻找那个位置而不是 0.