【问题标题】:Searching files in parallel并行搜索文件
【发布时间】:2016-02-08 12:23:34
【问题描述】:

我想创建一个命令,在给定数量的文件中并行搜索给定单词,其中...

ppatternsearch [-p n] word {files}
  1. ppatternsearch 是命令名
  2. -p 是一个定义并行化级别的选项
  3. n 是 -p 选项将执行的进程/线程数 为单词搜索创建

  4. word 是我要搜索的词

  5. files 是我将要搜索的文件。

我想通过两种方式做到这一点 - 一种使用processes,另一种使用threads。最后,父进程/主线程返回它找到正在搜索的单词的行数。

问题是,我已经开发了一些代码,但我碰壁了。我不知道从这里去哪里。

import argparse, os, sys, time

num_lines_with_pattern = []

def pattern_finder(pattern, file_searched):
    counter = 0
    with open(file_searched, 'r') as ficheiro_being_read:
        for line in ficheiro_being_read:
            if pattern in line:
                print line
                counter += 1
    num_lines_with_pattern.append(counter)

parser = argparse.ArgumentParser()
parser.add_argument('-p', type = int, default = 1, help = Defines command parallelization.')
args = parser.parse_args()

【问题讨论】:

    标签: python multithreading python-2.7 python-3.x subprocess


    【解决方案1】:

    问题可能是 I/O 受限,因此引入多个线程/进程不会让您的硬盘工作得更快。

    虽然它应该很容易检查。使用进程池运行pattern_finder()

    #!/usr/bin/env python
    from functools import partial
    from multiprocessing import Pool, cpu_count
    
    def pattern_finder(pattern, file_searched):
        ...
        return file_searched, number_of_lines_with_pattern
    
    if __name__ == "__main__":
        pool = Pool(n or cpu_count() + 1) 
        search = partial(pattern_finder, word)
        for filename, count in pool.imap_unordered(search, files):
            print("Found {count} lines in {filename}".format(**vars()))
    

    【讨论】:

      【解决方案2】:

      下一步是导入threadingmultiprocessing 并启动pattern_finder 适当的次数。

      您可能还想查看queue.Queue,以免打印结果混乱。

      【讨论】:

        猜你喜欢
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        • 1970-01-01
        • 2018-09-25
        • 2013-09-29
        • 1970-01-01
        相关资源
        最近更新 更多