How can I use the subprocess module (i.e. call
, check_call
and Popen
) to run more than one command?
For instance, lets say I wanted to execute the ls
command twice in quick sucession, the following syntax does not work
JavaScript
x
import subprocess
subprocess.check_call(['ls', 'ls'])
returns:
JavaScript
CalledProcessError: Command '['ls', 'ls']' returned non-zero exit status 2.
Advertisement
Answer
You can use &&
or ;
:
JavaScript
$ 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:
JavaScript
import subprocess
subprocess.run(["ls; ls"], shell=True)