Search code examples
pythonsubprocesspopen

When popen performs status check on service that dosen't exist error no results returned


I am attempting to use subprocess.Popen() to read a service status.

If I get an unrecognized service error the value, while printed to the screen, is not saved to out or err for later viewing.

If the service does exist, "is running" gets saved to the out value. I would like to accomplish the same results when the unrecognized error is encountered.

I have tried using subprocess.check_output but it is unrecognized.

If I use an existing service it works as desired.

My code:

p = subprocess.Popen(['service','PretendService','status'], stdout=subprocess.PIPE)

out,err = p.communicate()

Solution

  • You need to pipe stderr as well as stdout:

    p = subprocess.Popen(['service','PretendService','status'], 
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out,err = p.communicate()
    # Now err will have your error message