使用 Python 2 和 Python 3 时,我在对字符串进行 pickle 时得到不同的输出(我认为是由于 str
类型不同)。
Python 2:
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609]
>>> import pickle, base64
>>> a = pickle.dumps('test')
>>> base64.b64encode(a)
'Uyd0ZXN0JwpwMAou'
Python 3:
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609]
>>> import pickle, base64
>>> a = pickle.dumps('test')
>>> base64.b64encode(a)
b'gANYBAAAAHRlc3RxAC4='
如何修改代码以在 pickle 字符串时获得相同的结果?
编辑:
当使用protocol=2
时仍然得到不同的 pickle :
# Python 2
>>> base64.b64encode(pickle.dumps('test', protocol=2))
'gAJVBHRlc3RxAC4='
# Python 3
>>> base64.b64encode(pickle.dumps('test', protocol=2))
b'gAJYBAAAAHRlc3RxAC4='
最佳答案
Python 可以使用different stream versions pickle 时。 Python 2 和 Python 3 之间的默认版本有所不同。
显式传递协议(protocol)版本。使用 pickle.dumps('test', protocol=2)
获得跨版本的一致结果。
注意:确切的输出可能会改变,但 unpickling 结果保持不变,在 Python 2 中对“unicode”与“ascii”取模:
# Python 2.7 output:
>>> base64.b64encode(pickle.dumps('test', protocol=2))
'gAJVBHRlc3RxAC4='
# Decode output from Python 3:
>>> pickle.loads(base64.b64decode('gAJYBAAAAHRlc3RxAC4='))
u'test'
# Python 3.6 output:
>>> base64.b64encode(pickle.dumps('test', protocol=2))
b'gAJYBAAAAHRlc3RxAC4='
# Decoding Python 2's output:
>>> pickle.loads(base64.b64decode('gAJVBHRlc3RxAC4='))
'test' # Note, not u'test'.
关于Python 2 与 Python 3 字符串 pickle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48751831/