2014-10-29 52 views
1

我有一个我想用Python处理的文件。 这个文件中的每一行都是一个图像的路径,我想在每个图像上调用一个特征提取算法。Python中的多处理,每个进程处理文件的一部分

我想将文件分成更小的块,并且每个块将在并行独立进程中处理。 什么是用于Python中这种多处理的最先进的库或解决方案?

+0

https://docs.python.org/2/library/multiprocessing.html – Anentropic 2014-10-29 17:47:49

+0

Python有一个https://wiki.python.org/moin/GlobalInterpreterLock,这意味着线程只在每个线程花时间等待时才有用(如从服务器的响应)... ...积极做并行工作,你需要多处理 – Anentropic 2014-10-29 17:49:42

+0

谢谢Anenetropic,我会检查你的链接,我想我需要显式地分割数据(文件),并通过每个块作为参数然后到一个函数。 – Rami 2014-10-29 17:52:50

回答

4

你的描述表明,一个简单的线程(或进程)池会的工作:

#!/usr/bin/env python 
from multiprocessing.dummy import Pool # thread pool 
from tqdm import tqdm # $ pip install tqdm # simple progress report 

def mp_process_image(filename): 
    try: 
     return filename, process_image(filename), None 
    except Exception as e: 
     return filename, None, str(e) 

def main(): 
    # consider every non-blank line in the input file to be an image path 
    image_paths = (line.strip() 
        for line in open('image_paths.txt') if line.strip()) 
    pool = Pool() # number of threads equal to number of CPUs 
    it = pool.imap_unordered(mp_process_image, image_paths, chunksize=100) 
    for filename, result, error in tqdm(it): 
     if error is not None: 
      print(filename, error) 

if __name__=="__main__": 
    main() 

我认为process_image()是CPU绑定和它释放GIL即,它的主要工作在C扩展等OpenCV的。如果process_image()未释放GIL,则从Pool导入中删除单词.dummy以使用进程而不是线程。

+0

谢谢Sebastian提供优雅的解决方案。我最后的问题是,我怎样才能按顺序收集结果(第一块,第二块......的结果)? – Rami 2014-11-06 10:19:41

+1

@Rami:如果您需要结果,请使用'imap()'而不是'imap_unordered()'。 – jfs 2014-12-01 17:19:26