本文实例讲述了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#what-can-be-pickled-and-unpickled
3. https://github.com/uqfoundation/pathos
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 班得瑞原装进口《第五张新世纪专辑:迷雾森林+EP》1CD[APE/CUE分轨][334.2MB]
- 田震.1997-顺其自然(日版)【红星生产社】【WAV+CUE】
- 小虫.1996-想得太美【滚石】【WAV+CUE】
- 谢采妘.2016-邓丽君名曲专辑【丰荣】【WAV+CUE】
- 张含韵.2007-一人一梦【天中文化】【WAV+CUE】
- 蟑螂乐队.1999-帮个忙【福茂】【WAV+CUE】
- 张宇.2001-替身【EMI百代】【WAV+CUE】
- 班得瑞原装进口《第六张新世纪专辑:日光海岸》1CD[APE/CUE分轨][339.5MB]
- 班得瑞原装进口《第七张新世纪专辑:梦花园》1CD[APE/CUE分轨][331.4MB]
- 班得瑞原装进口《第八张新世纪专辑:琉璃湖畔》1CD[APE/CUE分轨][286.4MB]
- 魏如萱.2011-在哪里(EP)【添翼创越】【WAV+CUE】
- 群星.1981-新金曲奖·青年创作园地12合辑(喜玛拉雅复刻版)【歌林】【WAV+CUE】
- 麦洁文.1989-新曲与精丫新艺宝】【WAV+CUE】
- SNH48《薄荷糖 (Mint Candy)》[320K/MP3][33.72MB]
- SNH48《薄荷糖 (Mint Candy)》[FLAC/分轨][78.59MB]