Python multiprocess pool模块报错pickling error问题解决方法分析

yipeiwu_com5年前Python基础

本文实例讲述了Python multiprocess pool模块报错pickling error问题解决方法。分享给大家供大家参考,具体如下:

问题

之前在调用class内的函数用multiprocessing模块的pool函数进行多线程处理的时候报了以下下错误信息:

PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

查了下官方文档发现python默认只能pickle以下的类型:

  • None, True, and False
  • integers, floating point numbers, complex numbers
  • strings, bytes, bytearrays
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module (using def, not lambda)
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module
  • instances of such classes whose dict or the result of calling getstate() is picklable (see section -
  • Pickling Class Instances for details).

函数只能pickle在顶层定义的函数,很明显的class内的函数无法被pickle因此会报错。

import multiprocessing
def work():  # top-level 函数
  print "work!"
class Foo():
  def work(self): # 非top-level函数
    print "work"
pool1 = multiprocessing.Pool(processes=4)
foo = Foo()
pool1.apply_async(foo.work)
pool1.close()
pool1.join()
# 此时报错
pool2 = multiprocessing.Pool(processes=4)
pool2.apply_async(work)
pool2.close()
pool2.join()
# 此时工作正常

解决方案

调用pathos包下的multiprocessing模块代替原生的multiprocessing。pathos中multiprocessing是用dill包改写过的,dill包可以将几乎所有python的类型都serialize,因此都可以被pickle。或者也可以自己用dill写一个(有点重复造轮子之嫌啊)

参考

1. https://stackoverflow.com/questions/8804830/python-multiprocessing-picklingerror-cant-pickle-type-function
2. https://docs.python.org/3/library/pickle.html
3. https://github.com/uqfoundation/pathos

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python 命令行传入参数实现解析

python 命令行传入参数实现解析

创建 test.py 文件,代码如下: #!/usr/bin/python # -*- coding: gbk -*- import sys print sys.argv if __...

python OpenCV学习笔记实现二维直方图

python OpenCV学习笔记实现二维直方图

本文介绍了python OpenCV学习笔记实现二维直方图,分享给大家,具体如下: 官方文档 – https://docs.opencv.org/3.4.0/dd/d0d/tutori...

python基础教程之python消息摘要算法使用示例

python基础教程之python消息摘要算法使用示例

复制代码 代码如下:#! /usr/bin/python'''      File    &nb...

python实现上传样本到virustotal并查询扫描信息的方法

本文实例讲述了python实现上传样本到virustotal并查询扫描信息的方法。分享给大家供大家参考。具体方法如下: import simplejson import urlli...

Python2实现的LED大数字显示效果示例

Python2实现的LED大数字显示效果示例

本文实例讲述了Python2实现的LED大数字显示效果。分享给大家供大家参考,具体如下: #filename:bigNumber.py zero=['*******','* *'...