【发布时间】:2021-01-06 20:36:52
【问题描述】:
我试图总结一个目录中所有文件的大小,包括递归子目录。如果我只调用一次,相关函数 (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) 执行此操作。但是用硬编码值替换这一行并不能解决问题。即使在这一行设置断点也无济于事,因为它没有到达。
有人知道这个问题的原因是什么以及我该如何解决这个问题?
【问题讨论】:
标签: python python-3.x multiprocessing python-3.7