如何使用Python3多处理来运行多个Bash命令

2024-10-03 00:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个bash脚本来自动化多个工具。这个bash脚本接受一个字符串作为输入,并对其执行多个任务。 纸条的结构类似于

#!/bin/bash
tool1 $1
tool2 $1
tool3 $1
tool4 $1
tool5 $1

我想使用Python3多处理来运行n个并发/并行工具,以加快进程。 如何在Python中实现这一点


Tags: 工具字符串脚本bashbin结构python3纸条
2条回答

请使用multiprocessingsubprocess。使用自定义shell脚本时,如果它不在路径中,则使用脚本的完整路径。如果脚本与python脚本位于同一文件夹中,请使用./script.sh作为命令

还要确保您正在运行的脚本具有exec权限

from multiprocessing import Pool
import subprocess

def run_script(input):
    (command,arg_str)=input
    print("Starting command :{} with argument {}".format(command, arg_str))
    result = subprocess.call(command+" "+arg_str, shell=True) 
    print("Completed command :{} with argument {}".format(command, arg_str))
    return result

with Pool(5) as p: # choose appropriate level of parallelism
    # choose appropriate command and argument, can be fetched from sys.argv if needed
    exit_codes = p.map(run_script, [('echo','hello1'), ('echo','hello2')])
    print("Exit codes : {}".format(exit_codes))

您可以使用退出代码来验证完成状态。 样本输出:

Starting command :echo with argument hello1
Starting command :echo with argument hello2
hello1
hello2
Completed command :echo with argument hello1
Completed command :echo with argument hello2
Exit codes : [0, 0]

另一种方法(不使用python)是使用GNU并行。下面的命令执行与上面的python脚本相同的操作

parallel -k echo ::: 'hello1' 'hello2'

您可以像这样使用^{}^{}

import sys
import os 
import multiprocessing

tools = ['tool1', 'tool2', 'tool3', 'tool4', 'tool5']
arg1 = sys.argv[1]

p = multiprocessing.Pool(len(tools))
p.map(os.system, (t + ' ' + arg1 for t in tools))

这将启动len(tools)并行进程,这些进程将执行os.system('toolN arg')

不过,一般来说,您不需要Pool(len(tools)),因为如果启动的进程数超过机器上可用的核数N,则无法很好地扩展,因此您应该改为Pool()。这仍然会执行每个工具,但最多会同时执行N个

相关问题 更多 >