How to Execute Two Commands in Terminal Using Python'S Subprocess Module

How can I execute two commands in terminal using Python's subprocess module?

You can use && or ;:

$ ls && ls
file.txt file2.txt
file.txt file2.txt

$ ls; ls
file.txt file2.txt
file.txt file2.txt

The difference is that in case of && the second command will be executed only if the first one was successful (try false && ls) unlike the ; in which case the command will be executed independently from the first execution.

So, Python code will be:

import subprocess
subprocess.run(["ls; ls"], shell=True)

running multiple bash commands with subprocess

You have to use shell=True in subprocess and no shlex.split:

import subprocess

command = "echo a; echo b"

ret = subprocess.run(command, capture_output=True, shell=True)

# before Python 3.7:
# ret = subprocess.run(command, stdout=subprocess.PIPE, shell=True)

print(ret.stdout.decode())

returns:

a
b

How do I execute multiple shell commands with a single python subprocess call?

Use semicolon to chain them if they're independent.

For example, (Python 3)

>>> import subprocess
>>> result = subprocess.run('echo Hello ; echo World', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> result
CompletedProcess(args='echo Hello ; echo World', returncode=0, stdout=b'Hello\nWorld\n')

But technically that's not a pure Python solution, because of shell=True. The arg processing is actually done by shell. (You may think of it as of executing /bin/sh -c "$your_arguments")

If you want a somewhat more pure solution, you'll have to use shell=False and loop over your several commands. As far as I know, there is no way to start multiple subprocesses directly with subprocess module.



Related Topics



Leave a reply



Submit