16

So I am trying to store the output of a command into a variable. I do not want it to display output while running the command though...

The code I have right now is as follows...

def getoutput(*args):
    myargs=args
    listargs=[l.split(' ',1) for l in myargs]
    import subprocess
    output=subprocess.Popen(listargs[0], shell=False ,stdout=subprocess.PIPE)   
    out, error = output.communicate()
    return(out,error)


def main():

    a,b=getoutput("httpd -S")

if __name__ == '__main__':
    main()

If I put this in a file and execute it on the command line. I get the following output even though I do not have a print statement in the code. How can I prevent this, while still storing the output?

#python ./apache.py 
httpd: Could not reliably determine the server's fully qualified domain name, using xxx.xxx.xxx.xx for ServerName
Syntax OK

2 Answers 2

32

What you are seeing is standard-error output, not standard-output output. Stderr redirection is controlled by the stderr constructor argument. It defaults to None, which means no redirection occurs, which is why you see this output.

Usually it's a good idea to keep stderr output since it aids debugging and doesn't affect normal redirection (e.g. | and > shell redirection won't capture stderr by default). However you can redirect it somewhere else the same way you do stdout:

sp = subprocess.Popen(listargs[0], shell=False,
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = sp.communicate()

Or you can just drop stderr:

devnull = open(os.devnull, 'wb') #python >= 2.4
sp = subprocess.Popen(listargs[0], shell=False,
    stdout=subprocess.PIPE, stderr=devnull)

#python 3.x:
sp = subprocess.Popen(listargs[0], shell=False
    stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
Sign up to request clarification or add additional context in comments.

1 Comment

you should use os.devnull for portability to windows
3

You're catching stdout, but you're not catching stderr(standard error) which I think is where that message is coming from.

output=subprocess.Popen(listargs[0], shell=False ,stdout=subprocess.PIPE, stderr=STDOUT)

That will put anything from stderr into the same place as stdout.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.