python - 具有 namedtuple 的多处理对象 - pickle 错误

标签 python object multiprocessing pickle namedtuple

我在要放入多处理的对象中使用命名元组时遇到问题。我收到 pickle 错误。我尝试了其他 stackoverflow 帖子中的几件事,但我无法成功。这是我的代码结构:

package_main, test_module

 import myprogram.package_of_classes.data_object_module
 import ....obj_calculate

 class test(object):
       if __name__ == '__main__':
             my_obj=create_obj('myobject',['f1','f2'])
             input = multiprocessing.Queue()
             output = multiprocessing.Queue()
             input.put(my_obj)
             j=Process(target=obj_calculate, args=(input,output))
             j.start()

package_of_classes, data_object_module

 import collections
 import ....load_flat_file

 def get_ntuple_format(obj):
     nt_fields=''
     for fld in obj.fields:
         nt_fields=nt_fields+fld+', '
     nt_fields=nt_fields[0:-2]
     ntuple=collections.namedtuple('ntuple_format',nt_fields)
     return ntuple

 Class Data_obj:
    def __init__(self, name,fields):
        self.name=name
        self.fields=fields
        self.ntuple_form=get_ntuple_format(self)  

    def calculate(self):
        self.file_read('C:/files','division.txt')

    def file_read(self,data_directory,filename):
        output=load_flat_file(data_directory,filename,self.ntuple_form)
        self.data=output

utils_package,utils_module

def create_dataobj(name,fields):
    locals()[name]=Data_Obj(name,fields)
    return locals()[name]  

def obj_calculate(input,output):   
    obj=input.get()
    obj.calculate()
    output.put(obj)

加载模块

def load_flat_file(data_directory,filename,ntuple_form):
     csv.register_dialect('csvrd', delimiter='\t', quoting=csv.QUOTE_NONE)
     ListofTuples=[]
     with open(os.path.join(data_directory,filename), 'rb') as f:
          reader = csv.reader(f,'csvrd')
          for line in reader:
               if line:
                   ListofTuples.append(ntuple_form._make(line))
     return ListofTuples

我得到的错误是:

PicklingError: PicklingError: Can't pickle  class '__main__ . ntuple_format: it's not the same object as __ main __. ntuple_format

附言由于我是从一个大型项目中提取此示例代码,因此请忽略细微的不一致之处。

最佳答案

您不能 pickle 动态创建的类(在本例中为命名元组)(通过 get_ntuple_format)。对于一个可 pickle 的类,it has to be defined在可导入模块的顶层。

如果您只需要支持几种元组,请考虑提前在模块的顶层定义所有元组,然后动态选择正确的元组。如果您需要完全动态的容器格式,请考虑只使用 dict

关于python - 具有 namedtuple 的多处理对象 - pickle 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22304815/

相关文章:

Python pandas 数据透视/堆栈操作

python - 在 Spacy 中检测引理后的停用词

java - 从仅给定一个属性的 ArrayList 中删除一个对象

javascript - 如何从对象中获取值?

mysql - Perl、子项和共享数据

node.js - 多个 websocket 到多个服务器 : how do they communicate?

python - 突变后更新动态依赖的对象属性

python - 添加投影导入的 .asc 文件

javascript - 如何获取数组中的对象以显示在文档或控制台上

python - 处理大量数据而无需等待 block 完成