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
Convert Number Strings With Commas in Pandas Dataframe to Float
How to Restart a Program Based on User Input
Discord Bot Messaging a User With a Specific User Id
Finding Out Who Got the Highest Mark Among the Students
Importing Modules from Parent Folder
Python - How to Pad the Output of a MySQL Table
How to Check List Containing Nan
Reduce Multi-Index/Multi-Level Dataframe to Single Index, Single Level
Check Json Data Is None in Python
Python Pandas: Drop Rows of a Timeserie Based on Time Range
How to Print Float to N Decimal Places Including Trailing 0S
Python Xlsxwriter Set Border Around Multiple Cells
How to Name Dataframes Dynamically in Python
Check If a Specific Class and Value Exist in HTML Using Beautifulsoup Python