移植pickle py2到py3 字符串变成字节
Porting pickle py2 to py3 strings become bytes
我有一个用 python 2.7 创建的 pickle 文件,我正试图将其移植到 python 3.6。该文件通过 pickle.dumps(self.saved_objects, -1)
保存在 py 2.7 中
并通过 loads(data, encoding="bytes")
加载到 python 3.6(从以 rb
模式打开的文件)。如果我尝试以 r
模式打开并将 encoding=latin1
传递给 loads
,我会收到 UnicodeDecode 错误。当我将它作为字节流打开时,它会加载,但实际上每个字符串现在都是字节字符串。每个对象的 __dict__
键都是 b"a_variable_name"
然后在调用 an_object.a_variable_name
时会产生属性错误,因为 __getattr__
传递一个字符串而 __dict__
只包含字节。我觉得我已经尝试过参数和 pickle 协议的每一种组合。除了强行将所有对象的 __dict__
键转换为字符串外,我一头雾水。有什么想法吗?
** 跳至 2017 年 4 月 28 日更新以获得更好的示例
---------------------------------------- ---------------------------------------------- ------------------
** 2017 年 4 月 27 日更新
这个最小的例子说明了我的问题:
来自 py 2.7.13
import pickle
class test(object):
def __init__(self):
self.x = u"test ¢" # including a unicode str breaks things
t = test()
dumpstr = pickle.dumps(t)
>>> dumpstr
"ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb."
来自 py 3.6.1
import pickle
class test(object):
def __init__(self):
self.x = "xyz"
dumpstr = b"ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb."
t = pickle.loads(dumpstr, encoding="bytes")
>>> t
<__main__.test object at 0x040E3DF0>
>>> t.x
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
t.x
AttributeError: 'test' object has no attribute 'x'
>>> t.__dict__
{b'x': 'test ¢'}
>>>
---------------------------------------- ---------------------------------------------- ------------------
更新 2017 年 4 月 28 日
为了重现我的问题,我发布了我实际的原始泡菜数据 here
pickle 文件是在 python 2.7.13、windows 10 中使用
创建的
with open("raw_data.pkl", "wb") as fileobj:
pickle.dump(library, fileobj, protocol=0)
(协议 0,因此它是人类可读的)
要运行你需要classes.py
# classes.py
class Library(object): pass
class Book(object): pass
class Student(object): pass
class RentalDetails(object): pass
测试脚本在这里:
# load_pickle.py
import pickle, sys, itertools, os
raw_pkl = "raw_data.pkl"
is_py3 = sys.version_info.major == 3
read_modes = ["rb"]
encodings = ["bytes", "utf-8", "latin-1"]
fix_imports_choices = [True, False]
files = ["raw_data_%s.pkl" % x for x in range(3)]
def py2_test():
with open(raw_pkl, "rb") as fileobj:
loaded_object = pickle.load(fileobj)
print("library dict: %s" % (loaded_object.__dict__.keys()))
return loaded_object
def py2_dumps():
library = py2_test()
for protcol, path in enumerate(files):
print("dumping library to %s, protocol=%s" % (path, protcol))
with open(path, "wb") as writeobj:
pickle.dump(library, writeobj, protocol=protcol)
def py3_test():
# this test iterates over the different options trying to load
# the data pickled with py2 into a py3 environment
print("starting py3 test")
for (read_mode, encoding, fix_import, path) in itertools.product(read_modes, encodings, fix_imports_choices, files):
py3_load(path, read_mode=read_mode, fix_imports=fix_import, encoding=encoding)
def py3_load(path, read_mode, fix_imports, encoding):
from traceback import print_exc
print("-" * 50)
print("path=%s, read_mode = %s fix_imports = %s, encoding = %s" % (path, read_mode, fix_imports, encoding))
if not os.path.exists(path):
print("start this file with py2 first")
return
try:
with open(path, read_mode) as fileobj:
loaded_object = pickle.load(fileobj, fix_imports=fix_imports, encoding=encoding)
# print the object's __dict__
print("library dict: %s" % (loaded_object.__dict__.keys()))
# consider the test a failure if any member attributes are saved as bytes
test_passed = not any((isinstance(k, bytes) for k in loaded_object.__dict__.keys()))
print("Test %s" % ("Passed!" if test_passed else "Failed"))
except Exception:
print_exc()
print("Test Failed")
input("Press Enter to continue...")
print("-" * 50)
if is_py3:
py3_test()
else:
# py2_test()
py2_dumps()
将所有 3 个放在同一目录中,然后 运行 c:\python27\python load_pickle.py
首先为 3 个协议中的每一个创建 1 个 pickle 文件。然后 运行 与 python 3 相同的命令并注意它版本将 __dict__
键转换为字节。我让它工作了大约 6 个小时,但我一直想不通我是怎么把它弄坏的。
Question: Porting pickle py2 to py3 strings become bytes
下面给出的encoding='latin-1'
,可以。
b''
的问题是使用 encoding='bytes'
的结果。
这将导致 dict-keys 被解封为字节而不是 str.
问题数据是 datetime.date values '\x07á\x02\x10'
,从 raw-data.pkl
中的第 56 行开始。
如前所述,这是一个已知问题。
Unpickling python2 datetime under python3
http://bugs.python.org/issue22005
作为解决方法,我已经修补了 pickle.py
并获得了 unpickled object
,例如
book.library.books[0].rentals[0].rental_date=2017-02-16
这对我有用:
t = pickle.loads(dumpstr, encoding="latin-1")
Output:
<main.test object at 0xf7095fec>
t.__dict__={'x': 'test ¢'}
test ¢
测试 Python:3.4.2
简而言之,您正在用 RentalDetails
个对象中的 datetime.date
个对象击中 bug 22005。
这可以通过 encoding='bytes'
参数来解决,但这会使您的 类 的 __dict__
包含字节:
>>> library = pickle.loads(pickle_data, encoding='bytes')
>>> dir(library)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'bytes'
可以根据您的具体数据手动修复:
def fix_object(obj):
"""Decode obj.__dict__ containing bytes keys"""
obj.__dict__ = dict((k.decode("ascii"), v) for k, v in obj.__dict__.items())
def fix_library(library):
"""Walk all library objects and decode __dict__ keys"""
fix_object(library)
for student in library.students:
fix_object(student)
for book in library.books:
fix_object(book)
for rental in book.rentals:
fix_object(rental)
但这很脆弱,也很痛苦,您应该寻找更好的选择。
1) 实现 __getstate__
/__setstate__
将日期时间对象映射到一个完整的表示,例如:
class Event(object):
"""Example class working around datetime pickling bug"""
def __init__(self):
self.date = datetime.date.today()
def __getstate__(self):
state = self.__dict__.copy()
state["date"] = state["date"].toordinal()
return state
def __setstate__(self, state):
self.__dict__.update(state)
self.date = datetime.date.fromordinal(self.date)
2) 完全不要使用 pickle。按照 __getstate__
/__setstate__
,您可以在 类 中实施 to_dict
/from_dict
方法或类似方法,将其内容保存为 json 或其他一些纯格式。
最后一点,不需要在每个对象中都对库进行反向引用。
您应该将 pickle
数据视为特定于创建它的 Python 的(主要)版本。
(参见 Gregory Smith's message w.r.t. issue 22005。)
解决此问题的最佳方法是编写一个 Python 2.7 程序来读取腌制数据,并以中性格式将其写出。
快速查看您的实际数据,在我看来 SQLite 数据库适合作为交换格式,因为 Book
包含对 Library
和 [=13 的引用=].您可以为每个创建单独的表。
我有一个用 python 2.7 创建的 pickle 文件,我正试图将其移植到 python 3.6。该文件通过 pickle.dumps(self.saved_objects, -1)
并通过 loads(data, encoding="bytes")
加载到 python 3.6(从以 rb
模式打开的文件)。如果我尝试以 r
模式打开并将 encoding=latin1
传递给 loads
,我会收到 UnicodeDecode 错误。当我将它作为字节流打开时,它会加载,但实际上每个字符串现在都是字节字符串。每个对象的 __dict__
键都是 b"a_variable_name"
然后在调用 an_object.a_variable_name
时会产生属性错误,因为 __getattr__
传递一个字符串而 __dict__
只包含字节。我觉得我已经尝试过参数和 pickle 协议的每一种组合。除了强行将所有对象的 __dict__
键转换为字符串外,我一头雾水。有什么想法吗?
** 跳至 2017 年 4 月 28 日更新以获得更好的示例
---------------------------------------- ---------------------------------------------- ------------------
** 2017 年 4 月 27 日更新
这个最小的例子说明了我的问题:
来自 py 2.7.13
import pickle
class test(object):
def __init__(self):
self.x = u"test ¢" # including a unicode str breaks things
t = test()
dumpstr = pickle.dumps(t)
>>> dumpstr
"ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb."
来自 py 3.6.1
import pickle
class test(object):
def __init__(self):
self.x = "xyz"
dumpstr = b"ccopy_reg\n_reconstructor\np0\n(c__main__\ntest\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nVtest \xa2\np7\nsb."
t = pickle.loads(dumpstr, encoding="bytes")
>>> t
<__main__.test object at 0x040E3DF0>
>>> t.x
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
t.x
AttributeError: 'test' object has no attribute 'x'
>>> t.__dict__
{b'x': 'test ¢'}
>>>
---------------------------------------- ---------------------------------------------- ------------------
更新 2017 年 4 月 28 日
为了重现我的问题,我发布了我实际的原始泡菜数据 here
pickle 文件是在 python 2.7.13、windows 10 中使用
创建的with open("raw_data.pkl", "wb") as fileobj:
pickle.dump(library, fileobj, protocol=0)
(协议 0,因此它是人类可读的)
要运行你需要classes.py
# classes.py
class Library(object): pass
class Book(object): pass
class Student(object): pass
class RentalDetails(object): pass
测试脚本在这里:
# load_pickle.py
import pickle, sys, itertools, os
raw_pkl = "raw_data.pkl"
is_py3 = sys.version_info.major == 3
read_modes = ["rb"]
encodings = ["bytes", "utf-8", "latin-1"]
fix_imports_choices = [True, False]
files = ["raw_data_%s.pkl" % x for x in range(3)]
def py2_test():
with open(raw_pkl, "rb") as fileobj:
loaded_object = pickle.load(fileobj)
print("library dict: %s" % (loaded_object.__dict__.keys()))
return loaded_object
def py2_dumps():
library = py2_test()
for protcol, path in enumerate(files):
print("dumping library to %s, protocol=%s" % (path, protcol))
with open(path, "wb") as writeobj:
pickle.dump(library, writeobj, protocol=protcol)
def py3_test():
# this test iterates over the different options trying to load
# the data pickled with py2 into a py3 environment
print("starting py3 test")
for (read_mode, encoding, fix_import, path) in itertools.product(read_modes, encodings, fix_imports_choices, files):
py3_load(path, read_mode=read_mode, fix_imports=fix_import, encoding=encoding)
def py3_load(path, read_mode, fix_imports, encoding):
from traceback import print_exc
print("-" * 50)
print("path=%s, read_mode = %s fix_imports = %s, encoding = %s" % (path, read_mode, fix_imports, encoding))
if not os.path.exists(path):
print("start this file with py2 first")
return
try:
with open(path, read_mode) as fileobj:
loaded_object = pickle.load(fileobj, fix_imports=fix_imports, encoding=encoding)
# print the object's __dict__
print("library dict: %s" % (loaded_object.__dict__.keys()))
# consider the test a failure if any member attributes are saved as bytes
test_passed = not any((isinstance(k, bytes) for k in loaded_object.__dict__.keys()))
print("Test %s" % ("Passed!" if test_passed else "Failed"))
except Exception:
print_exc()
print("Test Failed")
input("Press Enter to continue...")
print("-" * 50)
if is_py3:
py3_test()
else:
# py2_test()
py2_dumps()
将所有 3 个放在同一目录中,然后 运行 c:\python27\python load_pickle.py
首先为 3 个协议中的每一个创建 1 个 pickle 文件。然后 运行 与 python 3 相同的命令并注意它版本将 __dict__
键转换为字节。我让它工作了大约 6 个小时,但我一直想不通我是怎么把它弄坏的。
Question: Porting pickle py2 to py3 strings become bytes
下面给出的encoding='latin-1'
,可以。
b''
的问题是使用 encoding='bytes'
的结果。
这将导致 dict-keys 被解封为字节而不是 str.
问题数据是 datetime.date values '\x07á\x02\x10'
,从 raw-data.pkl
中的第 56 行开始。
如前所述,这是一个已知问题。
Unpickling python2 datetime under python3
http://bugs.python.org/issue22005
作为解决方法,我已经修补了 pickle.py
并获得了 unpickled object
,例如
book.library.books[0].rentals[0].rental_date=2017-02-16
这对我有用:
t = pickle.loads(dumpstr, encoding="latin-1")
Output:
<main.test object at 0xf7095fec>
t.__dict__={'x': 'test ¢'}
test ¢
测试 Python:3.4.2
简而言之,您正在用 RentalDetails
个对象中的 datetime.date
个对象击中 bug 22005。
这可以通过 encoding='bytes'
参数来解决,但这会使您的 类 的 __dict__
包含字节:
>>> library = pickle.loads(pickle_data, encoding='bytes')
>>> dir(library)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'bytes'
可以根据您的具体数据手动修复:
def fix_object(obj):
"""Decode obj.__dict__ containing bytes keys"""
obj.__dict__ = dict((k.decode("ascii"), v) for k, v in obj.__dict__.items())
def fix_library(library):
"""Walk all library objects and decode __dict__ keys"""
fix_object(library)
for student in library.students:
fix_object(student)
for book in library.books:
fix_object(book)
for rental in book.rentals:
fix_object(rental)
但这很脆弱,也很痛苦,您应该寻找更好的选择。
1) 实现 __getstate__
/__setstate__
将日期时间对象映射到一个完整的表示,例如:
class Event(object):
"""Example class working around datetime pickling bug"""
def __init__(self):
self.date = datetime.date.today()
def __getstate__(self):
state = self.__dict__.copy()
state["date"] = state["date"].toordinal()
return state
def __setstate__(self, state):
self.__dict__.update(state)
self.date = datetime.date.fromordinal(self.date)
2) 完全不要使用 pickle。按照 __getstate__
/__setstate__
,您可以在 类 中实施 to_dict
/from_dict
方法或类似方法,将其内容保存为 json 或其他一些纯格式。
最后一点,不需要在每个对象中都对库进行反向引用。
您应该将 pickle
数据视为特定于创建它的 Python 的(主要)版本。
(参见 Gregory Smith's message w.r.t. issue 22005。)
解决此问题的最佳方法是编写一个 Python 2.7 程序来读取腌制数据,并以中性格式将其写出。
快速查看您的实际数据,在我看来 SQLite 数据库适合作为交换格式,因为 Book
包含对 Library
和 [=13 的引用=].您可以为每个创建单独的表。