Fix Python – How to suppress or capture the output of


Asked By – planetp

From the examples in docs on it seems like there shouldn’t be any output from["ls", "-l"])  # doesn't capture output

However, when I try it in a python shell the listing gets printed. I wonder if this is the default behaviour and how to suppress the output of run().

Now we will see solution for issue: How to suppress or capture the output of


Here is how to suppress output, in order of decreasing levels of cleanliness. They assume you are on Python 3.

  1. You can redirect to the special subprocess.DEVNULL target.
import subprocess['ls', '-l'], stdout=subprocess.DEVNULL)
# The above only redirects stdout...
# this will also redirect stderr to /dev/null as well['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Alternatively, you can merge stderr and stdout streams and redirect
# the one stream to /dev/null['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
  1. If you want a fully manual method, can redirect to /dev/null by opening the file handle yourself. Everything else would be identical to method #1.
import os
import subprocess

with open(os.devnull, 'w') as devnull:['ls', '-l'], stdout=devnull)

Here is how to capture output (to use later or parse), in order of decreasing levels of cleanliness. They assume you are on Python 3.

NOTE: The below examples use text=True.

  • This causes the STDOUT and STDERR to be captured as str instead of bytes.
    • Omit text=True to get bytes data
  • text=True is Python >= 3.7 only, use universal_newlines=True on Python <= 3.6
    • universal_newlines=True is identical to text=True but more verbose to type but should exist on all Python versions
  1. If you simply want to capture both STDOUT and STDERR independently, AND you are on Python >= 3.7, use capture_output=True.
import subprocess

result =['ls', '-l'], capture_output=True, text=True)
  1. You can use subprocess.PIPE to capture STDOUT and STDERR independently. This works on any version of Python that supports
import subprocess

result =['ls', '-l'], stdout=subprocess.PIPE, text=True)

# To also capture stderr...
result =['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# To mix stdout and stderr into a single string
result =['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

This question is answered By – SethMMorton

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0