简体   繁体   中英

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

How can I use the subprocess module (ie 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.

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM