38

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
triple fault
  • 13,410
  • 8
  • 32
  • 45
  • 1
    related: [How to hide output of subprocess in Python 2.7](http://stackoverflow.com/q/11269575) – jfs Jul 28 '15 at 19:10
  • The above is pretty much a duplicate, except the specific method (`call` versus `check_output`). – user202729 Dec 05 '21 at 16:50

1 Answers1

69

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
    )

math2001
  • 4,167
  • 24
  • 35
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • For Python 3: `output = subprocess.check_output("netstat -nptl".split(), stderr=subprocess.STDOUT)` is a right approach? – alper Apr 07 '20 at 13:26
  • 1
    @alper: no, that redirects stderr to stdout. To *suppress* stderr, use `output = subprocess.check_output("netstat -nptl".split(), stderr=subprocess.DEVNULL)` – Martijn Pieters Apr 07 '20 at 13:30
  • 2
    from python 3.5 on you have also `subprocess.run()`, which should be used for newer code. `output = subprocess.run(check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout` – gelonida Apr 17 '20 at 13:34
  • 1
    @gelonida: sure, but note that this question is tagged with `python-2.7`. – Martijn Pieters Apr 17 '20 at 20:24
  • 1
    @MartijnPieters True. I just thought, that python 2.7 will become less and less common and that python 3 users might also stumble upon this question. You think I should delete my comment? – gelonida Apr 18 '20 at 00:44