我创建了一个bash脚本来自动化多个工具。这个bash脚本接受一个字符串作为输入,并对其执行多个任务。脚本的结构类似于
#!/bin/bash
tool1 $1
tool2 $1
tool3 $1
tool4 $1
tool5 $1我想使用Python3多处理来运行n个工具的并发/并行,以加速进程。如何在Python中实现?
发布于 2020-04-23 09:55:52
您可以像这样结合使用multiprocessing.pool.Pool和os.system:
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))这将启动将执行os.system('toolN arg')的len(tools)并行进程。
不过,一般来说,您不想要Pool(len(tools)),因为如果您启动的进程数超过机器上可用的核心数量N,那么它就不能很好地伸缩,所以您应该使用Pool()。这将仍然执行每个工具,但它最多只能并发执行N个。
发布于 2020-04-23 10:05:11
请使用multiprocessing和subprocess。使用自定义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'https://stackoverflow.com/questions/61377540
复制相似问题