gpt4 book ai didi

python - 如何在 Linux 上并行化 Python 程序

转载 作者:IT王子 更新时间:2023-10-29 01:12:30 39 4
gpt4 key购买 nike

我有一个脚本,它接受输入文件名列表并循环处理它们以生成每个输入文件的输出文件,所以我认为这种情况可以很容易地并行化。

我有一个 8 核机器。

我尝试在此命令上使用 -parallel 标志:

python perfile_code.py list_of_files.txt

但我无法让它工作,即具体问题是:如何在 Linux 中使用 bash 中的并行命令和 python 命令,以及上述特定情况的参数。

有一个 Linux 并行命令(sudo apt-get install parallel),我在某处读到它可以完成这项工作,但我不知道如何使用它。

大多数互联网资源都在 python 中解释了如何操作但它可以在 bash 中完成吗?

请帮忙,谢谢。

Based on an answer, here is a working example that is still not working, please suggest how to make it work.

我有一个包含 2 个文件的文件夹,在此示例中,我只想用不同的名称并行创建它们的副本。

# filelist is the directory containing two file names, a.txt and b.txt.
# a.txt is the first file, b.xt is the second file
# i pass an .txt file with both the names to the main program

from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import sys

def translate(filename):
print(filename)
f = open(filename, "r")
g = open(filename + ".x", , "w")
for line in f:
g.write(line)

def main(path_to_file_with_list):
futures = []
with ProcessPoolExecutor(max_workers=8) as executor:
for filename in Path(path_to_file_with_list).open():
executor.submit(translate, "filelist/" + filename)
for future in as_completed(futures):
future.result()

if __name__ == "__main__":
main(sys.argv[1])

最佳答案

根据您的评论,

@Ouroborus no, no consider this opensource.com/article/18/5/gnu-parallel i want to run a python program along with this parallel..for a very specific case..if an arbitrary convert program can be piped to parallel ..why wouldn't a python program?

我认为这可能有帮助:

convert 不是任意选择的。之所以选择它,是因为它是一个更为知名的程序,可以(粗略地)将通过命令行提供的单个输入文件映射到也通过命令行提供的单个输出文件。

典型的 shell for 循环可用于遍历列表。在您链接的文章中,他们展示了一个示例

for i in *jpeg; do convert $i $i.png ; done

这(再次粗略地)获取文件名列表并将它们一个接一个地应用到命令模板,然后运行该命令。

这里的问题是 for 必须等到一个命令完成后再运行下一个命令,因此可能无法充分利用当今的多核处理器。

parallelfor 的替代品。它假设一个命令可以同时执行多次,每个命令都有不同的参数,而每个实例不会相互干扰。

在文章中,他们展示了一个使用parallel

的命令
find . -name "*jpeg" | parallel -I% --max-args 1 convert % %.png

这等同于前面的for 命令。区别(仍然大致)是 parallel 同时运行模板命令的多个变体,而不必等待每个变体完成。


对于您的具体情况,为了能够使用parallel,您需要:

  • 调整您的 Python 脚本,使其通过命令行接受一个输入(例如文件名)和一个输出(也可能是文件名)。
  • 弄清楚如何设置 parallel,以便它可以接收这些文件名的列表,以便插入到命令模板中,从而在每个文件上单独运行 python 脚本。

关于python - 如何在 Linux 上并行化 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509214/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com