Kiran Varghese Kiran Varghese - 21 days ago 6
Python Question

Get output and return codes of multiple interdependent commands using subprocess

import subprocess
with open ("log.txt",'a') as log:
output = subprocess.Popen("ech ;echo hello", shell=True, stdout=log, stderr=subprocess.STDOUT)
print output.wait() # prints 0


ech
writes "/bin/sh: ech: command not found" into "log.txt". But the return code is 0 (SUCCESS) because the last command was successful. I want to get individual command return codes and not the return code of just the last command.

Also, assume that the commands are dependent -
For example:
cd .. ; pwd
- They should not be split and run as two subprocess calls, because then
pwd
would not take into account the effect of
cd ..


The example just above is only for clarification purposes. Please don't recommend solving it by using
cwd
.

Answer

You need to do what I always recommend people do as the very first lines of any Bash script:

set -e (quite standard)
set -o pipefail (requires Bash 3 or later)

Then, whenever a command (or part of a pipeline) fails, the whole script will fail. This will cure your problem by stopping as soon as ech is not found.