pickle 可用于python序列化和反序列化
现在有5种不同的协议进行序列化
Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.
Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.
Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.
Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.
当我们在使用pickle.dump进行序列化的时候,如果不指定Protocol ,python2会默认使用2,python3会默认使用3
这样当使用一个版本进行序列化的时候,在想使用另一个版本进行加载就会出现错误,例如我使用python2来反序列化python3产生的文件,出现了这样的错误
ValueError: unsupported pickle protocol: 3
解决方法(使用python3反序列化 在设置python2可使用的Protocol参数进行序列化)
import pickle
testpkl = pickle.loads(open("./test.pkl", "rb").read())
pickle.dump(testpkl, open("testpkl_py2.pkl","wb"), protocol=2)
参考:
https://blog.csdn.net/zziahgf/article/details/80253125
https://docs.python.org/3/library/pickle.html#pickle.dump