Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress stderr within subprocess.check_output()

I'm trying to find a way to ignore the stderr stream (something similar to 2> /dev/null):

output = subprocess.check_output("netstat -nptl".split()) 

What should I add to the above command to achieve this?

like image 758
Naftaly Avatar asked Jul 28 '15 17:07

Naftaly


People also ask

What is subprocess Check_output in Python?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

How do I turn off subprocess output in Python?

To hide output of subprocess with Python, we can set stdout to subprocess. DEVNULL`. to output the echo command's output to dev null by setting the stdout to subprocess.

What is the return type of subprocess Check_output?

CalledProcessError Exception raised when a process run by check_call() or check_output() returns a non-zero exit status. returncode Exit status of the child process.

How do I capture the output of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.


1 Answers

Just tell subprocess to redirect it for you:

import subprocess      output = subprocess.check_output(     "netstat -nptl".split(), stderr=subprocess.DEVNULL ) 

For python 2, it's a bit more verbose.

import os import subprocess  with open(os.devnull, 'w') as devnull:     output = subprocess.check_output(         "netstat -nptl".split(), stderr=devnull     )  
like image 162
Martijn Pieters Avatar answered Sep 22 '22 13:09

Martijn Pieters