Suppressing

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

# To redirect stdout (only):
subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.DEVNULL
)

# to redirect stderr to /dev/null as well:
subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.DEVNULL,
    stderr = subprocess.DEVNULL
)

# Alternatively, you can merge stderr and stdout streams and redirect
# the one stream to /dev/null
subprocess.run(
    ['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:
    subprocess.run(
        ['ls', '-l'],
        stdout = devnull
    )

Capturing

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 universal_newlines=True (Python <= 3.6).

  • This causes the STDOUT and STDERR to be captured as str instead of bytes.
    • Omit universal_newlines=True to get bytes data
  • Python >= 3.7 accepts text=True as a short form for universal_newlines=True
  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 = subprocess.run(
    ['ls', '-l'],
    capture_output = True, # Python >= 3.7 only
    text = True # Python >= 3.7 only
)
print(result.stdout)
print(result.stderr)
  1. You can use subprocess.PIPE to capture STDOUT and STDERR independently. This works on any version of Python that supports subprocess.run.
import subprocess

result = subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.PIPE,
    universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)

# To also capture stderr...
result = subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
    universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)
print(result.stderr)

# To mix stdout and stderr into a single string
result = subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.PIPE,
    stderr = subprocess.STDOUT,
    universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)
Answer from SethMMorton on Stack Overflow
Top answer
1 of 2
443

Suppressing

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

# To redirect stdout (only):
subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.DEVNULL
)

# to redirect stderr to /dev/null as well:
subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.DEVNULL,
    stderr = subprocess.DEVNULL
)

# Alternatively, you can merge stderr and stdout streams and redirect
# the one stream to /dev/null
subprocess.run(
    ['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:
    subprocess.run(
        ['ls', '-l'],
        stdout = devnull
    )

Capturing

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 universal_newlines=True (Python <= 3.6).

  • This causes the STDOUT and STDERR to be captured as str instead of bytes.
    • Omit universal_newlines=True to get bytes data
  • Python >= 3.7 accepts text=True as a short form for universal_newlines=True
  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 = subprocess.run(
    ['ls', '-l'],
    capture_output = True, # Python >= 3.7 only
    text = True # Python >= 3.7 only
)
print(result.stdout)
print(result.stderr)
  1. You can use subprocess.PIPE to capture STDOUT and STDERR independently. This works on any version of Python that supports subprocess.run.
import subprocess

result = subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.PIPE,
    universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)

# To also capture stderr...
result = subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE,
    universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)
print(result.stderr)

# To mix stdout and stderr into a single string
result = subprocess.run(
    ['ls', '-l'],
    stdout = subprocess.PIPE,
    stderr = subprocess.STDOUT,
    universal_newlines = True # Python >= 3.7 also accepts "text=True"
)
print(result.stdout)
2 of 2
31

ex: to capture the output of ls -a

import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
2 weeks ago - Subclass of SubprocessError, raised when a timeout expires while waiting for a child process. ... Command that was used to spawn the child process. ... Timeout in seconds. ... Output of the child process if it was captured by run() or check_output(). Otherwise, None.
🌐
Reddit
reddit.com › r/learnpython › printing output from subprocess.run
r/learnpython on Reddit: Printing output from subprocess.run
October 27, 2023 -

I'm not getting an error but its not really printed what i wanted

I was trying to get these echo commands to show in either idle or running .py script

import subprocess

allscripts = ["./scripty1", "./scripty2", "./scripty3", "./scripty4", "./scripty5"]
for x in allscripts: subprocess.run([x], shell=True, capture_output=True) print(subprocess.check_output)

All it prints is this though

λ /bin/python /mnt/Stor2/Media/Share/DevShare/Py/InstallScript/InstallScript.py<function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040><function check_output at 0x7f7f2a94c040>

🌐
GitHub
gist.github.com › nawatts › e2cdca610463200c12eac2a14efc0bfb
capture-and-print-subprocess-output.py · GitHub
However, I'd like to keep a bash subprocess running and feeding it commands when I wanna. I've tried calling your snipped with only ["bash"] so it stays open, adding stdin as PIPE and then writing commands to stdin and it locks. ... This was very helpful! Thank you! ... This worked very well for me, but I noticed that at times it would not get the last line of stdout. I added this code snippet · # Ensure all remaining output is processed while True: line = process.stdout.readline() if not line: break buf.write(line) sys.stdout.write(line)
🌐
Computer Science Atlas
csatlas.com › python-subprocess-run-stdout-stderr
Python 3: Get Standard Output and Standard Error from subprocess.run() — Computer Science Atlas
July 14, 2021 - On Python 3.7 or higher, if we pass in capture_output=True to subprocess.run(), the CompletedProcess object returned by run() will contain the stdout (standard output) and stderr (standard error) output of the subprocess:
🌐
DataCamp
datacamp.com › tutorial › python-subprocess
An Introduction to Python Subprocess: Basics and Examples | DataCamp
September 12, 2025 - Using the Python subprocess module ... programs with your Python code. For example, you can use the subprocess module to run a shell command, like ls or ping, and get the output of that command in your Python code....
🌐
GeeksforGeeks
geeksforgeeks.org › python › retrieving-the-output-of-subprocesscall-in-python
Retrieving the output of subprocess.call() in Python - GeeksforGeeks
July 23, 2025 - The subprocess.check_output() function runs a command and returns its output as a byte string. You can decode this byte string to get a string.
Find elsewhere
🌐
Earthly
earthly.dev › blog › python-subprocess
How to Use Python's Subprocess Module - Earthly Blog
July 11, 2023 - Running subprocess.run(command) prints the output of the command onto the console, and the stdout attribute is None by default if we don’t capture the output. When you run Bash commands such as chmod to change file permissions or the sleep ...
🌐
Learn by Example
learnbyexample.github.io › tips › python-tip-11
Python tip 11: capture external command output
June 1, 2022 - >>> import subprocess >>> cmd = ('date', '-u', '+%A') >>> p = subprocess.run(cmd, capture_output=True, text=True) >>> p CompletedProcess(args=('date', '-u', '+%A'), returncode=0, stdout='Wednesday\n', stderr='') >>> p.stdout 'Wednesday\n' >>> subprocess.check_output(cmd, text=True) 'Wednesday\n' With check_output(), you'll get an exception if something goes wrong with the command being executed.
🌐
End Point Dev
endpointdev.com › blog › 2015 › 01 › getting-realtime-output-using-python
Getting realtime output using Python Subprocess | End Point Dev
January 28, 2015 - ... To run a process and read all of its output, set the stdout value to PIPE and call communicate(). import subprocess process = subprocess.Popen(['echo', '"Hello stdout"'], stdout=subprocess.PIPE) stdout = process.communicate()[0] print 'STDOUT:{}'.format(stdout)
🌐
TestMu AI Community
community.testmuai.com › ask a question
How can I retrieve the output of a process run using Python subprocess.call? - Ask a Question - TestMu AI Community
December 3, 2024 - How can I retrieve the output of a process run using Python subprocess.call? I want to capture the output of a process executed using subprocess.call(). When I attempt to pass a StringIO.StringIO object to the stdout parameter, I encounter the following error: Traceback (most recent call last): File " ", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call return Popen(*popenargs, **kwargs).wait() File "/Lib...
🌐
Python Forum
python-forum.io › thread-2392.html
[subprocess]>Run a cmd command and get output into a variable
Hello All, I'd like to run a windows cmd and get the result in a variable..it works well for a command but not for another... **confused** Here is : Command 'whoami' > Works !! **smile** [icode] import subprocess p1=subprocess.Popen(['whoami...
🌐
Python for Network Engineers
pyneng.readthedocs.io › en › latest › book › 12_useful_modules › subprocess.html
subprocess - Python for network engineers
By default, run() function returns the result of a command execution to a standard output stream. If you want to get the result of command execution, add stdout argument with value subprocess.PIPE:
🌐
GitHub
gist.github.com › almoore › c6fd2d041ad4f4bf2719a89c9b454f7e
Getting realtime output using Python Subprocess · GitHub
To run a process and read all of its output, set the stdout value to PIPE and call communicate(). import subprocess process = subprocess.Popen(['echo', '"Hello stdout"'], stdout=subprocess.PIPE) stdout = process.communicate()[0] print('STDO...
🌐
Python Morsels
pythonmorsels.com › running-subprocesses-in-python
Running subprocesses in Python - Python Morsels
March 6, 2025 - This version also captures the output and ensures that the output is text. Here's a version of our Python script that uses this custom run function: import subprocess import sys def run(command, *args, **kwargs): """Run subprocess and check for successful status code.""" return subprocess.run( [command, *args], capture_output=True, check=True, text=True, **kwargs, ) # Try to determine the default branch name process = run("git", "branch", "--format=%(refname:short)") lines = process.stdout.splitlines() if "main" in lines: print("main") elif "master" in lines: print("master") elif "trunk" in lines: print("trunk") else: sys.exit("Default branch is unknown")