【发布时间】:2014-11-04 21:57:52
【问题描述】:
我正在阅读一个类似的线程,其中 OP 希望使用多处理处理函数中的每一行(找到 here)。这个有趣的问题的答案如下:
from multiprocessing import Pool
def process_line(line):
return "FOO: %s" % line
if __name__ == "__main__":
pool = Pool(4)
with open('file.txt') as source_file:
# chunk the work into batches of 4 lines at a time
results = pool.map(process_line, source_file, 4)
我想知道您是否可以这样做,但不是返回处理的每一行,而是将其写入另一个文件。
基本上我想看看是否有一种方法可以 MP 读取和写入文件以便按行拆分它。假设我想要每个文件 100,000 行。
from multiprocessing import Pool
def write_lines(line):
#need method to write lines to multiple files, perhaps a Queue?
if __name__ == "__main__":
#all my procs
pool = Pool()
with open('file.txt') as source_file:
# chunk the work into batches of 4 lines at a time
results = pool.map(process_line, source_file, 100000)
我可以使用 MP Queue 将文件拆分为单独的 Queue 对象,然后用写出所有行的作业填充每个处理器,但我仍然必须先通读文件。那么它是否总是完全受 IO 限制而永远无法以有效的方式成为 MP?
【问题讨论】:
标签: python multithreading io multiprocessing