0

I need to run subprocess commands in for loop parallelly without interrupting one another. I have more than 100 shell commands. Some run for a short period and some take time. I don't want to wait for long-running commands. Below are the example. "cmds" is a list of commands

for cmd in cmds:
    push=subprocess.Popen(cmd, shell=True,stdout = subprocess.PIPE)
    push.wait()
    print(push.communicate()[0])
6
  • use a process pool Commented Jul 8, 2021 at 6:20
  • Does this answer your question? How do I parallelize a simple Python loop? Commented Jul 8, 2021 at 6:21
  • How can I call subprocess through process pool? No of commands can vary in list Commented Jul 8, 2021 at 6:22
  • put the command inside a function Commented Jul 8, 2021 at 6:23
  • Okay I will try this Commented Jul 8, 2021 at 6:24

2 Answers 2

2

Use a process pool, specify how many processes should run in parallel and let the pool handle the job scheduling:

from multiprocessing import Pool

def run_command(cmd):
    push=subprocess.Popen(cmd, shell=True,stdout = subprocess.PIPE)
    push.wait()
    return push.communicate()[0]

pool = Pool(processes=8)
results = pool.map(run_command, cmds)

for result in results:
    print(result)
Sign up to request clarification or add additional context in comments.

Comments

0

Through this we can run multiple commands in async way

import subprocess
import asyncio
import time

def background(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)

    return wrapped

@background
def func1():
    cmd = 'echo "fun1 1"; sleep 5; echo "func1 2"; sleep 5; echo "func1 3"'
    subprocess.call(cmd, shell=True)

@background
def func2():
    cmd = 'echo "fun2 1"; sleep 5; echo "func2 2"; sleep 5; echo "func2 3"'
    subprocess.call(cmd, shell=True)


func1()
func2()

print('loop finished')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.