我想在多個檔案上并行執行一個函式,并將結果存盤在以檔案名作為鍵的字典中。
但我從中得到的只是<multiprocessing.pool.ApplyResult at 0x7f37065fac40>字典的每個條目。
如何直接獲取每個字典條目中的結果?
此外,我想監控整個任務的進度(有多少檔案已被處理(例如列印檔案 i/total)。
我嘗試了以下方法:
from multiprocessing import Pool
import os
def process(file):
# processings ...
return results
pool = Pool()
result_dict = {}
for file in os.listdir("<DIRPATH>"):
result_dict[file] = pool.apply_async(process, file)
pool.close()
pool.join()
uj5u.com熱心網友回復:
該multiprocessing.pool.Pool.apply_async方法回傳一個multiprocessing.pool.AsyncResult代表“未來”結果的實體。也就是說,要獲得實際結果,您必須get在此實體上呼叫方法,該方法將阻塞,直到實際結果可用,然后回傳該結果。因此,您需要按如下方式修改代碼:
from multiprocessing import Pool
import os
def process(file):
# processings ...
return results
pool = Pool()
result_dict = {}
for file in os.listdir("<DIRPATH>"):
result_dict[file] = pool.apply_async(process, file)
for k, v in result_dict.items():
# Update key with the actual result:
result_dict[k] = v.get()
pool.close()
pool.join()
至于關于顯示進度的第二個問題,您必須發布一個新問題(您不能在一個帖子上發布多個完全不相關的問題)。如果你愿意,一旦你這樣做了,你可以在這個答案中添加評論,并附上新問題的鏈接,如果可以的話,我會看看它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453716.html
上一篇:在并行流上傳播偵探包
