Kiran Varghese Kiran Varghese - 1 year ago 49
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

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
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download