运行 N 个进程在 linux 中并行
running N process in parallel in linux
我正在尝试创建 python 脚本,该脚本将从文件中读取命令,然后同时读取 运行 N 个命令。这就是我目前所拥有的并行执行 运行 N 的内容。
from subprocess import Popen
import time
with open('commands.txt') as f:
commands = f.read().split('\n')
test_number = 20
while True:
processes = [];time.sleep(6)
for com in commands[test_number -20:test_number]:
processes.append(Popen(com, shell=True))
time.sleep(6)
for i, process in enumerate(processes):
process.wait()
print(f"Command #{i} finished")
test_number += 20
我需要在每个命令之间设置 6 秒延迟,在我的解决方案中,最快的命令必须等待最慢的命令,然后 运行在 while(true)
中执行另一个命令。有更好的方法吗?
- 我更喜欢 python 解决方案,但也可以使用 C
您可以使用 multiprocess.Pool
创建一个子进程池和 运行 您的 shell 脚本在其中,就像 .
中描述的那样
import time
from subprocess import Popen
from multiprocessing import Pool
with open('commands.txt') as f:
commands = f.read().split('\n')
def run_com(com, i):
Popen(com, shell=True)
# time.sleep(10) # here only for testing
print(f"Command #{i} finished")
test_number = 20
pool = Pool(test_number)
for i, com in enumerate(commands):
time.sleep(6) # wait 6 seconds between starting each command
pool.apply_async(run_com, (com, i)) # run command in pool
pool.close() # once tasks are completed the worker processes exit
pool.join() # waits for all the tasks to finish
通过这种方式,池将跟踪其工作进程中有哪些被占用,并在空闲时将任务分配给其中一个,这样您的进程将不会停止其他进程。
我正在尝试创建 python 脚本,该脚本将从文件中读取命令,然后同时读取 运行 N 个命令。这就是我目前所拥有的并行执行 运行 N 的内容。
from subprocess import Popen
import time
with open('commands.txt') as f:
commands = f.read().split('\n')
test_number = 20
while True:
processes = [];time.sleep(6)
for com in commands[test_number -20:test_number]:
processes.append(Popen(com, shell=True))
time.sleep(6)
for i, process in enumerate(processes):
process.wait()
print(f"Command #{i} finished")
test_number += 20
我需要在每个命令之间设置 6 秒延迟,在我的解决方案中,最快的命令必须等待最慢的命令,然后 运行在 while(true)
中执行另一个命令。有更好的方法吗?
- 我更喜欢 python 解决方案,但也可以使用 C
您可以使用 multiprocess.Pool
创建一个子进程池和 运行 您的 shell 脚本在其中,就像
import time
from subprocess import Popen
from multiprocessing import Pool
with open('commands.txt') as f:
commands = f.read().split('\n')
def run_com(com, i):
Popen(com, shell=True)
# time.sleep(10) # here only for testing
print(f"Command #{i} finished")
test_number = 20
pool = Pool(test_number)
for i, com in enumerate(commands):
time.sleep(6) # wait 6 seconds between starting each command
pool.apply_async(run_com, (com, i)) # run command in pool
pool.close() # once tasks are completed the worker processes exit
pool.join() # waits for all the tasks to finish
通过这种方式,池将跟踪其工作进程中有哪些被占用,并在空闲时将任务分配给其中一个,这样您的进程将不会停止其他进程。