Python:使用多处理池时使用队列写入单个文件

时间:2014-10-27 20:57:53

标签: python queue multiprocessing pool

我想要以各种方式解析数十万个文本文件。我想将输出保存到单个文件而不会出现同步问题。我一直在使用多处理池来节省时间,但我无法弄清楚如何组合池和队列。

以下代码将保存infile名称以及文件中连续" x" s的最大数量。但是,我希望所有进程将结果保存到同一个文件,而不是像我的示例中那样保存到不同的文件。对此的任何帮助将不胜感激。

import multiprocessing

with open('infilenamess.txt') as f:
    filenames = f.read().splitlines()

def mp_worker(filename):
 with open(filename, 'r') as f:
      text=f.read()
      m=re.findall("x+", text)
      count=len(max(m, key=len))
      outfile=open(filename+'_results.txt', 'a')
      outfile.write(str(filename)+'|'+str(count)+'\n')
      outfile.close()

def mp_handler():
    p = multiprocessing.Pool(32)
    p.map(mp_worker, filenames)

if __name__ == '__main__':
    mp_handler()

3 个答案:

答案 0 :(得分:29)

多处理池为您实现队列。只需使用池方法将工作者返回值返回给调用者。 imap效果很好:

import multiprocessing 
import re

def mp_worker(filename):
    with open(filename) as f:
        text = f.read()
    m = re.findall("x+", text)
    count = len(max(m, key=len))
    return filename, count

def mp_handler():
    p = multiprocessing.Pool(32)
    with open('infilenamess.txt') as f:
        filenames = [line for line in (l.strip() for l in f) if line]
    with open('results.txt', 'w') as f:
        for result in p.imap(mp_worker, filenames):
            # (filename, count) tuples from worker
            f.write('%s: %d\n' % result)

if __name__=='__main__':
    mp_handler()

答案 1 :(得分:4)

我接受了接受的答案,并将其简化为我自己对其工作原理的理解。我在这里发布它,以防它帮助其他人。

import multiprocessing

def mp_worker(number):
    number += 1
    return number

def mp_handler():
    p = multiprocessing.Pool(32)
    numbers = list(range(1000))
    with open('results.txt', 'w') as f:
        for result in p.imap(mp_worker, numbers):
            f.write('%d\n' % result)

if __name__=='__main__':
    mp_handler()

答案 2 :(得分:1)

这是我使用multiprocessing Manager对象的方法。这种方法的好处是,当处理掉到了run_multi()函数中的带有块的管理器时,文件编写器队列将自动关闭,从而使代码非常易于阅读,并且无需麻烦就可以停止监听队列。 / p>

from functools import partial
from multiprocessing import Manager, Pool, Queue
from random import randint
import time

def run_multi():
    input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    with Manager() as manager:
        pool = Pool()  # By default pool will size depending on cores available
        message_queue = manager.Queue()  # Queue for sending messages to file writer listener
        pool.apply_async(file_writer, (message_queue, ))  # Start file listener ahead of doing the work
        pool.map(partial(worker, message_queue=message_queue), input)  # Partial function allows us to use map to divide workload

def worker(input: int, message_queue: Queue):
    message_queue.put(input * 10)
    time.sleep(randint(1, 5))  # Simulate hard work

def file_writer(message_queue: Queue):
    with open("demo.txt", "a") as report:
        while True:
            report.write(f"Value is: {message_queue.get()}\n")

if __name__ == "__main__":
    run_multi()