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]
请使用
multiprocessing
和subprocess
。使用自定义shell脚本时,如果它不在路径中,则使用脚本的完整路径。如果脚本与python脚本位于同一文件夹中,请使用./script.sh
作为命令还要确保您正在运行的脚本具有exec权限
您可以使用退出代码来验证完成状态。 样本输出:
另一种方法(不使用python)是使用GNU并行。下面的命令执行与上面的python脚本相同的操作
您可以像这样使用^{} 和^{} :
这将启动
len(tools)
并行进程,这些进程将执行os.system('toolN arg')
不过,一般来说,您不需要
Pool(len(tools))
,因为如果启动的进程数超过机器上可用的核数N,则无法很好地扩展,因此您应该改为Pool()
。这仍然会执行每个工具,但最多会同时执行N个相关问题 更多 >
编程相关推荐