Python multiprocess pool模塊報錯pickling error問題解決方法分析
本文實例講述了Python multiprocess pool模塊報錯pickling error問題解決方法。分享給大家供大家參考,具體如下:
問題
之前在調(diào)用class內(nèi)的函數(shù)用multiprocessing模塊的pool函數(shù)進行多線程處理的時候報了以下下錯誤信息:
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
查了下官方文檔發(fā)現(xiàn)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).
函數(shù)只能pickle在頂層定義的函數(shù),很明顯的class內(nèi)的函數(shù)無法被pickle因此會報錯。
import multiprocessing
def work(): # top-level 函數(shù)
print "work!"
class Foo():
def work(self): # 非top-level函數(shù)
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()
# 此時工作正常
解決方案
調(diào)用pathos包下的multiprocessing模塊代替原生的multiprocessing。pathos中multiprocessing是用dill包改寫過的,dill包可以將幾乎所有python的類型都serialize,因此都可以被pickle?;蛘咭部梢宰约河胐ill寫一個(有點重復(fù)造輪子之嫌啊)
參考
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
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
NumPy實現(xiàn)ndarray多維數(shù)組操作
NumPy一個非常重要的作用就是可以進行多維數(shù)組的操作,這篇文章主要介紹了NumPy實現(xiàn)ndarray多維數(shù)組操作,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2021-05-05
Python批量實現(xiàn)橫屏轉(zhuǎn)豎屏的視頻處理工具
這篇文章主要為大家詳細介紹了如何使用Python和Tkinter框架開發(fā)一個視頻處理器應(yīng)用,用于批量橫屏轉(zhuǎn)豎屏視頻處理,支持多種視頻格式和編碼選擇,需要的可以了解下2025-02-02

