gpt4 book ai didi

python - 用 python 3 解开一个 python 2 对象

转载 作者:IT老高 更新时间:2023-10-28 21:06:27 25 4
gpt4 key购买 nike

我想知道是否有办法使用 Python 3.4 加载在 Python 2.4 中 pickle 的对象。

我一直在对大量公司遗留代码运行 2to3 以使其保持最新状态。

完成此操作后,在运行文件时出现以下错误:

  File "H:\fixers - 3.4\addressfixer - 3.4\trunk\lib\address\address_generic.py"
, line 382, in read_ref_files
d = pickle.load(open(mshelffile, 'rb'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal
not in range(128)

查看竞争中的 pickle 对象,它是 dict 中的 dict,包含 str 类型的键和值。

所以我的问题是:有没有办法使用 python 3.4 加载最初在 python 2.4 中 pickle 的对象?

最佳答案

您必须告诉 pickle.load() 如何将 Python 字节串数据转换为 Python 3 字符串,或者您可以告诉 pickle 将它们保留为字节。

默认是尝试将所有字符串数据解码为 ASCII,但解码失败。见 pickle.load() documentation :

Optional keyword arguments are fix_imports, encoding and errors, which are used to control compatibility support for pickle stream generated by Python 2. If fix_imports is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The encoding and errors tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects.

将编码设置为latin1可以直接导入数据:

with open(mshelffile, 'rb') as f:
d = pickle.load(f, encoding='latin1')

但您需要确认您的所有字符串均未使用错误的编解码器进行解码; Latin-1 适用于任何输入,因为它将字节值 0-255 直接映射到前 256 个 Unicode 代码点。

另一种方法是使用 encoding='bytes' 加载数据,然后解码所有 bytes 键和值。

请注意,直到 3.6.8、3.7.2 和 3.8.0 之前的 Python 版本,unpickling of Python 2 datetime object data is broken除非你使用 encoding='bytes'

关于python - 用 python 3 解开一个 python 2 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28218466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com