【发布时间】:2017-07-15 14:02:00
【问题描述】:
如何更改 Python multiprocessing 库使用的序列化方法?特别是,默认序列化方法使用pickle 库和该版本 Python 的默认 pickle 协议版本。默认的 pickle 协议是 Python 2.7 中的版本 2 和 Python 3.6 中的版本 3。如何在 Python 3.6 中将协议版本设置为 2,以便可以使用 multiprocessing 库中的一些类(如 Client 和 Listener)在 Python 2.7 运行的服务器处理和客户端之间进行通信Python 3.6 运行的进程?
(旁注:作为测试,我修改了line 206 of multiprocessing/connection.py,将protocol=2 添加到dump() 调用中以强制协议版本为2,并且我的客户端/服务器进程在我的有限测试中运行,服务器由2.7 和 3.6 的客户端)。
在 Python 3.6 中,合并了 patch 以设置序列化程序,但补丁未记录在案,我还没有弄清楚如何使用它。这是我尝试使用它的方式(我也将它发布到我链接到的 Python 票证上):
pickle2reducer.py:
from multiprocessing.reduction import ForkingPickler, AbstractReducer
class ForkingPickler2(ForkingPickler):
def __init__(self, *args):
if len(args) > 1:
args[1] = 2
else:
args.append(2)
super().__init__(*args)
@classmethod
def dumps(cls, obj, protocol=2):
return ForkingPickler.dumps(obj, protocol)
def dump(obj, file, protocol=2):
ForkingPickler2(file, protocol).dump(obj)
class Pickle2Reducer(AbstractReducer):
ForkingPickler = ForkingPickler2
register = ForkingPickler2.register
dump = dump
在我的客户中:
import pickle2reducer
multiprocessing.reducer = pickle2reducer.Pickle2Reducer()
在使用multiprocessing 做任何其他事情之前先放在顶部。执行此操作时,我仍然在由 Python 2.7 运行的服务器上看到 ValueError: unsupported pickle protocol: 3。
【问题讨论】:
-
上述问题 (bugs.python.org/issue28053) 正在等待 PR 以添加文档和改进。 github.com/python/cpython/pull/15058/files
标签: python serialization pickle python-multiprocessing