Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am calling shell script from Python script using subprocess module. In my below python code, shell_script is my actual script.

proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable='/bin/bash')
(stdout, stderr) = proc.communicate()
if proc.returncode != 0:
    print("Errors while executing the shell script: %s" % stderr)
    break

And here is my shell script which is failing for sure as I am deliberately making it fail and then I am echoing out this echo "Folder doesn't exist on $machine"; error on the shell script and then exiting with status 1.

But this error message doesn't get showed up on the Python script side as I am printing it out using stderr if you see my above python code.

for machine in "${MACHINES[@]}"; do
   dircheck=($(ssh -o "StrictHostKeyChecking no" david@${machine} [[ ! -d "$dir3" ]] \&\& exit 1 \; ls -t1 "$dir3"))

   if [[ $? != 0 ]] ;then
       echo "Folder doesn't exist on $machine";
       exit 1
   fi

   if [[ "${dircheck[@]}" = '' ]] ;then
       echo "0 Files on server $machine in $dir3";
       exit 1
   fi
done

Any idea what's wrong and what should I do? I am just trying to reflect error message whatever is happening on the shell script to the Python script whenever there is any error.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Your shell script doesn't write to standard error, as echo outputs to standard output. You need to redirect the output to standard error as follows:

echo "Folder doesn't exist on $machine" >&2

and

echo "0 Files on server $machine in $dir3" >&2
share|improve this answer
    
Thanks chepner. Quick and silly question do I need semicolon after >&2? Meaning it should be like this echo "Folder doesn't exist on $machine" >&2;? –  AKIWEB Apr 14 at 19:20
    
You would only need the semicolon if you wanted another command on the same line, for example, echo "..." >&2; exit 1. –  chepner Apr 14 at 19:31
    
@AKIWEB: if you want all output from the shell script to go to stderr; you could put at the top: exec >&2 –  J.F. Sebastian Apr 14 at 19:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.