g4ur4v
g4ur4v

Reputation: 3288

Python script not returning correct error status

I am new to python,Need some help!

PYTHON VERSION: 2.7

SCRIPT

import subprocess
import sys

HOST="user@machine"
COMMAND="ps -fu user | grep \"XYZ\" |grep -v grep |wc -l"  #Command to be run

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

result = ssh.stdout.readlines()

if result == []:
        error = ssh.stderr.readlines()
        print >>sys.stderr, "ERROR: %s" % error
else:
        result = [qaz.strip('\n') for qaz in result]
        print result

This script results in this output:

['0']

PROBLEM

Even If change the COMMAND to be executed on other machine to some irrelevant string,I am not getting the error message ,say I change the command to below value and run the script again.

COMMAND="adsasdadsps -fu user | grep \"XYZ\" |grep -v grep |wc -l"

The script now also results in same output.

['0']

But When I changed the command as below.

COMMAND="asdadasd"

Then I got the output.

ERROR: ['ksh: line 1: asdadasd: not found\n']

Can anyone help with me understand why I am not getting error message for

COMMAND="adsasdadsps -fu user | grep \"XYZ\" |grep -v grep |wc -l"

Upvotes: 0

Views: 226

Answers (2)

SethMMorton
SethMMorton

Reputation: 48775

You might want to change your logic so that you check if the stderr is empty or not:

result = ssh.stdout.readlines()
error = ssh.stderr.readlines()

if error:
    print >>sys.stderr, "ERROR: {}".format(''.join(error))
else:
    print ''.join(result)

Note that I have changed the error and result messages so they get printed without the brackets. Also, it's better to test if a list is empty by using the fact that an empty list is False instead of comparing to [].

Upvotes: 1

tdelaney
tdelaney

Reputation: 77367

Its a shell thing. The shell sets up the full pipeline even though the first command errors. wc -l reports that it counted '0' lines and that's where the ['0'] comes from. You could add a 'bash' tag to this post for more details, but I think that its a fork/exec that emits the error after the pipeline is setup (that is, the top level shell doesn't know the program didn't exist, its a forked copy that got that bit of news).

The return code isn't going to help (the shell gives you the return code of the last program in the pipeline). You can read stderr but be careful of programs that emit chatty traffic on stderr even though its not a real error.

Upvotes: 1

Related Questions