ws_*_*421 6 python serialization pickle python-multiprocessing
如何更改 Pythonmultiprocessing库使用的序列化方法?特别是,默认序列化方法使用pickle具有该版本 Python 的默认 pickle 协议版本的库。默认的 pickle 协议在 Python 2.7 中是版本 2,在 Python 3.6 中是版本 3。如何在 Python 3.6 中将协议版本设置为 2,以便我可以使用库中的一些类(如Client和Listener)在multiprocessingPython 2.7 运行的服务器处理和 Python 3.6 运行的客户端进程之间进行通信?
(旁注:作为测试,我修改了第 206 行multiprocessing/connection.py,添加protocol=2到dump()调用中以强制协议版本为 2,并且我的客户端/服务器进程在我有限的测试中工作,服务器由 2.7 运行,客户端由 3.6 运行)。
在 Python 3.6 中,合并了一个补丁来设置序列化程序,但是该补丁没有记录,我还没有弄清楚如何使用它。这是我尝试使用它的方式(我也将其发布到我链接到的 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
Run Code Online (Sandbox Code Playgroud)
在我的客户中:
import pickle2reducer
multiprocessing.reducer = pickle2reducer.Pickle2Reducer()
Run Code Online (Sandbox Code Playgroud)
在使用multiprocessing. ValueError: unsupported pickle protocol: 3当我这样做时,我仍然在由 Python 2.7 运行的服务器上看到。
如果您使用的是多处理“上下文”对象,我相信您所指的补丁有效。
使用你的 pickle2reducer.py,你的客户端应该从:
import pickle2reducer
import multiprocessing as mp
ctx = mp.get_context()
ctx.reducer = pickle2reducer.Pickle2Reducer()
Run Code Online (Sandbox Code Playgroud)
并ctx具有与 multiprocessing.
希望有帮助!
| 归档时间: |
|
| 查看次数: |
4033 次 |
| 最近记录: |