Suppress stderr within subprocess.check_output()

Question:

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?

Asked By: Naftaly

||

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
    )

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.