RonW
RonW

Reputation: 1

Using subprocess to start multiple programs

I'm trying to use a Python script to start multiple programs. The issue that I'm facing is that while the first of those programs executes as expected in a shell, the second program never does. Is there a way to start the first program and not have subprocess wait to start the second?

I've tried using the call function from the subprocess module, having the main program wait 5 seconds and then start the second.

import subprocess

subprocess.call(['xxx', 'xxxxxx', 'xxxxxxxx', 'shell=True'])
time.sleep(5)
subprocess.call(['xxx', '-x', 'xxxxxx'])

I want the program to start each of these programs in a shell, but only the first program ever starts.

Upvotes: 0

Views: 1132

Answers (1)

john-hen
john-hen

Reputation: 4866

Use the Popen constructor from the subprocess module directly in order to start processes in the background.

As it effectively starts a process, but doesn't wait for it to finish, I like to rename it to start in code. Like so:

from subprocess import Popen as start
process = start('python process.py')

As in your example, you may just give the process, or each of the processes, enough time to finish. However, it may be advisable to wait for them to finish individually before you exit the calling script:

from subprocess import Popen as start

processes = []

for i in range(3):
    process = start(f'python process{i}.py')
    processes.append(process)

for process in processes:
    process.wait()

Refer to the documentation of the subprocess module in order to decide if adding the option shell=True is actually needed for the purpose of running your external process.

Upvotes: 0

Related Questions