0

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

import subprocess
subprocess.check_call(['ls', 'ls'])

returns:

CalledProcessError: Command '['ls', 'ls']' returned non-zero exit status 2.
1
  • 1
    Does for _ in range(2): subprocess.Popen('ls') not work for your solution? Commented Feb 11, 2019 at 14:37

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

Just execute the command twice.

import subprocess
subprocess.check_call(['ls'])
subprocess.check_call(['ls'])

That should be quick enough.

Edit

If you want to execute two commands in the same shell, write a shell script that executes them and run this script from Python.

1 Comment

I'm afraid my question is a simplification of a more complicated problem. I actually do need to execute two commands one after the other, in the same shell. Thanks for responding though.
1

This following code would work. But wouldn't it be better to just execute the ls command twice?

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

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.