【问题标题】:Parallelize a function to run on multiple files [closed]并行化一个函数以在多个文件上运行[关闭]
【发布时间】:2016-06-19 18:25:03
【问题描述】:

我有一个解析 .txt 文件以匹配某些字符串的 python 脚本(带有方法)。我还有其他四个 .txt 文件,它们都位于同一目录中,包括原始文件。如何并行化我的代码,以便我可以在所有代码上运行 python 脚本?

【问题讨论】:

  • 你只需要在你的 python 中使用多线程和需要处理的文件的全局共享列表。每个线程从该共享列表中获取一个条目并相应地处理该文件。文件名可以很容易地通过参数传递。你可以使用 system.argv

标签: python parsing command-line parallel-processing


【解决方案1】:

例如使用concurrent.futures:

from concurrent.futures import ThreadPoolExecutor

list_of_files = ["foo1", "foo2", "foo3", "foo4"]

with ThreadPoolExecutor(max_workers=4) as e:
    futures = [e.submit(your_parsing_function(f) for f in list_of_files]

您可以使用as_completed 方法添加可选的后处理逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2019-07-10
    • 1970-01-01
    • 2016-06-14
    • 2022-12-01
    • 2019-12-16
    • 2019-01-18
    • 2018-07-13
    相关资源
    最近更新 更多