如何更改多处理模块使用的序列化方法?

2024-04-26 18:01:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何更改Pythonmultiprocessing库使用的序列化方法?特别是,默认序列化方法使用pickle库,其中包含该版本Python的默认pickle协议版本。默认的pickle协议在python2.7中是version2,在python3.6中是version3。如何在Python3.6中将协议版本设置为2,以便可以使用Client库中的某些类(如Client和{})在Python2.7运行的服务器处理和Python3.6运行的客户机进程之间进行通信?在

(旁注:作为一个测试,我修改了line 206 of ^{},将protocol=2添加到dump()调用中,以强制协议版本为2,我的客户机/服务器进程在我的有限测试中工作,服务器由2.7运行,客户机由3.6运行)。在

在Python3.6中,合并了一个patch来设置序列化程序,但是这个补丁没有文档记录,我还没有弄清楚如何使用它。下面是我尝试使用它的方法(我也将此贴到了链接到的Python票证上):

泡菜2减速器.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

在我的客户身上:

^{pr2}$

在使用multiprocessing执行任何其他操作之前。当我这样做时,在python2.7运行的服务器上仍然可以看到ValueError: unsupported pickle protocol: 3。在


Tags: 方法版本服务器clientobj协议客户机序列化
1条回答
网友
1楼 · 发布于 2024-04-26 18:01:55

我相信,如果您使用多处理"context" object,那么您所指的修补程序是有效的。在

用你的泡菜2减速器.py,您的客户应以以下内容开头:

import pickle2reducer
import multiprocessing as mp

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

并且ctxmultiprocessing具有相同的API。在

希望有帮助!在

相关问题 更多 >