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?
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.
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.
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.
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With