Prevent the subprocess. Open from output in python

So, I'm trying to save the output of a command to a variable. I do not want it to display the output during the execution of the command, though ...

The code I have 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 if I don’t have a print instruction in the code. How can I prevent this while maintaining output?

 #python ./apache.py httpd: Could not reliably determine the server fully qualified domain name, using xxx.xxx.xxx.xx for ServerName Syntax OK 
+7
source share
2 answers

What you see is the output of the standard error, not the output of the standard output. Stderr redirection is controlled by the stderr constructor argument. By default, it is None , which means that the redirect does not occur, so you see this output.

It is generally recommended to store the output of stderr, as it helps debug and does not affect the normal redirection (for example, | and > redirecting the shell will not fix stderr by default). However, you can redirect it to another place 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 simply remove 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) 
+17
source

You are catching stdout, but you are not catching stderr (standard error), and I think where this message came from.

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

This will put anything from stderr in the same place as stdout.

+2
source

All Articles