2017-07-15 39 views
1

如何更改Python multiprocessing库使用的序列化方法?特别是,默认序列化方法使用pickle库和该版本的Python的默认pickle协议版本。默认的pickle协议是Python 2.7中的版本2和Python 3.6中的版本3。如何在Python 3.6中将协议版本设置为2,以便我可以使用multiprocessing库中的某些类(如ClientListener)在Python 2.7运行的服务器处理和Python 3.6运行的客户端进程之间进行通信?如何更改Python多处理使用的序列化方法?

(附注:作为一个测试,我加入protocol=2dump()调用强制协议版本2和我的客户机/服务器进程在我有限的测试工作由2.7上运行的服务器和客户端通过修改line 206 of multiprocessing/connection.py 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

回答

2

我相信你指的补丁工程如果你使用多处理"context" object

使用您pickle2reducer.py,客户端应该开始:

import pickle2reducer 
import multiprocessing as mp 

ctx = mp.get_context() 
ctx.reducer = pickle2reducer.Pickle2Reducer() 

而且ctx具有相同的API multiprocessing

希望有帮助!

+0

这似乎是正确的方式来使用该修补程序。我没有看到如何在特定情况下使用上下文。我使用'from multiprocessing.connection import Client,Listener'和'from multiprocessing.managers import BaseManager,NameSpaceProxy',这四个类都不能从上下文对象访问。我可以这样做:'multiprocessing.context._default_context.reducer = Pickle2Reducer()'。 –

相关问题