Use subprocess.check_output()
with the shell=True
option, but heed the security warning re untrusted inputs if it applies to you.
import subprocess
command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull'
try:
output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as exc:
print("subprocess failed with return code {}".format(exc.returncode))
print("message: {}".format(exc.message))
After this output
contains the combined stdout of the executed processes, if it was successful. Otherwise you need to handle a CalledProcessError exception.
Alternatively, if you can not guarantee that the command strings are secure, you can perform each command in turn, progressing to the next command only if the current command's return code is 0 i.e. CalledProcessError
is not raised.
import subprocess
import shlex
command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull'
output = []
try:
for cmd in command.split('&&'):
output.append(subprocess.check_output(shlex.split(cmd)))
except subprocess.CalledProcessError as exc:
print("{!r} failed with return code {}".format(' '.join(exc.cmd), exc.returncode))
else:
print(''.join(output))
While this is more secure with regard to shell command injection, it is still possible for sensitive arguments to be sniffed by other users for example with ps
.