【问题标题】:Python 2 vs Python 3 string picklingPython 2 与 Python 3 字符串酸洗
【发布时间】:2018-07-22 22:32:26
【问题描述】:

在使用 Python 2 和 Python 3 时,我得到不同的输出酸洗字符串(我想是由于不同的 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='

如何修改代码以在酸洗字符串时获得相同的结果?

编辑:

当使用protocol=2 时仍然得到不同的泡菜:

# Python 2
>>> base64.b64encode(pickle.dumps('test', protocol=2))
'gAJVBHRlc3RxAC4='

# Python 3
>>> base64.b64encode(pickle.dumps('test', protocol=2))
b'gAJYBAAAAHRlc3RxAC4='

【问题讨论】:

  • 在您的pickle.dumps() 电话中更改the protocol。 Possibly related question
  • 尝试将protocol=2, fix_imports=True添加到版本3的dumps语句中
  • 您想要相同的输出还是数据兼容性?在 Python 2 和 Python 3 中,任何一种腌制变体都可以与pickle.loads() 一起正常工作。我想数据填充之类的东西可能会有所不同,从而导致序列化的变化。我怀疑区别在于 unicode 与字节字符串。

标签: python python-3.x python-2.7 pickle


【解决方案1】:

Python 在酸洗时可以使用different stream versions。 Python 2 和 Python 3 的默认版本不同。

明确传递协议版本。使用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'.

【讨论】:

  • 添加了 protocol=2 输出编辑
猜你喜欢
  • 1970-01-01
  • 2012-05-03
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多