如何更改Python使用的序列化方法multiprocessing
图书馆?特别是,默认的序列化方法使用pickle
具有该版本 Python 的默认 pickle 协议版本的库。默认的pickle协议在Python 2.7中是版本2,在Python 3.6中是版本3。如何在 Python 3.6 中将协议版本设置为 2,以便我可以使用一些类(例如Client
and Listener
) 在里面multiprocessing
用于在 Python 2.7 运行的服务器进程和 Python 3.6 运行的客户端进程之间进行通信的库?
(旁注:作为测试,我修改了第 206 行multiprocessing/connection.py https://github.com/python/cpython/blob/5458647bb867770fc3d830a618cef6994fdfac4b/Lib/multiprocessing/connection.py#L206通过增加protocol=2
to the dump()
调用强制协议版本为 2,我的客户端/服务器进程在我的有限测试中工作,服务器运行 2.7,客户端运行 3.6)。
在 Python 3.6 中,patch http://bugs.python.org/issue28053被合并以设置序列化器,但补丁没有记录,我还没有弄清楚如何使用它。以下是我尝试使用它的方法(我也将其发布到我链接到的 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
。我仍然看到ValueError: unsupported pickle protocol: 3
当我这样做时,在 Python 2.7 运行的服务器上。