簡體   English   中英

使用來自多處理的池時出現 TypeError(python 3.7)

[英]TypeError while using Pool from multiprocessing (python 3.7)

我試圖總結一個目錄中所有文件的大小,包括遞歸子目錄。 如果我只調用一次,相關的 function ( self._count ) 工作得很好。 但是對於大量文件,我想使用multiprocessing來使程序更快。 以下是代碼的相關部分。

self._sum_dict將給定字典的相同鍵的值相加。
self._get_file_type返回文件應放置的類別( stats的鍵)。
self._categories包含所有可能類別的列表。
number_of_threats指定應使用的工人數量。
path保存第一句中所指目錄的路徑。

import os
from multiprocessing import Pool

def _count(self, path):
    stats = dict.fromkeys(self._categories, 0)
    try:
        dir_list = os.listdir(path)
    except:
        # I do some warning here, but removed it for SSCCE
        return stats

    for element in dir_list:
        new_path = os.path.join(path, element)

        if os.path.isdir(new_path):
            add_stats = self._count(new_path)
            stats = self._sum_dicts([stats, add_stats])
        else:
            file_type = self._get_file_type(element)
            try:
                size = os.path.getsize(new_path)
            except Exception as e:
                # I do some warning here, but removed it for SSCCE
                continue

            stats[file_type] += size

    return stats

files = []
dirs = []
for e in dir_list:
    new_name = os.path.join(path, e)
    if os.path.isdir(new_name):
        dirs.append(new_name)
    else:
        files.append(new_name)

with Pool(processes=number_of_threats) as pool:
    res = pool.map(self._count, dirs)

self._stats = self._sum_dicts(res)

我知道,此代碼不會考慮path中的文件,但這是我可以輕松添加的內容。 執行代碼時出現以下異常。

Exception has occurred: TypeError
cannot serialize '_io.TextIOWrapper' object
...
line ... in ...
res = pool.map(self._count, dirs)

我發現,在共享進程之間的資源時可能會發生此異常,據我所知,我只使用stats = dict.fromkeys(self._categories, 0) 但是用硬編碼值替換這一行並不能解決問題。 即使在這一行放置一個斷點也無濟於事,因為它沒有達到。

有誰知道這個問題的原因是什么以及我該如何解決這個問題?

問題是你試圖傳遞“自我”。 如果 self 有一個 Stream object 它不能被序列化。

嘗試將多處理代碼移到 class 之外。

Python 多處理啟動一個新的解釋器,如果您嘗試訪問無法腌制(或序列化)的共享代碼,它會失敗。 通常它不會在您認為它崩潰的地方崩潰……但是在嘗試接收 object 時。 我將使用線程的代碼轉換為多處理,即使我沒有發送或使用這些對象,我也遇到了很多奇怪的錯誤,但我使用了它們的父級( self )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM