Featured Article

"Python Subprocess: Capture Output Efficiently"

Christopher Jun 29, 2026

Mastering Python Subprocess: Capturing Output

Python Input & Output Explained 🐍 | Beginner's Guide
Python Input & Output Explained 🐍 | Beginner's Guide

In the realm of Python programming, the subprocess module is a powerful tool that allows us to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. One of the most common use cases is capturing the output of these subprocesses. Let's delve into the intricacies of Python's subprocess module, focusing on capturing output.

Python Notes
Python Notes

Understanding the Basics

Before we dive into capturing output, let's ensure we understand the basics of using the subprocess module. The most fundamental function is subprocess.run(), which executes a command and returns a CompletedProcess object. This object contains the return code, stdout, stderr, and other attributes of the process.

Python printoutput reference guide
Python printoutput reference guide

Using subprocess.run()

Here's a simple example of using subprocess.run() to run a command and print its output:

Python Input Output Guide for Beginners (Complete Syntax)
Python Input Output Guide for Beginners (Complete Syntax)

```python import subprocess result = subprocess.run(['ls', '-l'], capture_output=True, text=True) print(result.stdout) ```

Capturing Standard Output (stdout)

The above example demonstrates capturing the standard output (stdout) of a command. The capture_output=True argument tells subprocess.run() to capture both stdout and stderr. The text=True argument ensures that the output is decoded as text.

Capturing Stderr Separately

the screenshoter is showing what to do with it and how to use it
the screenshoter is showing what to do with it and how to use it

Sometimes, you might want to capture stderr separately. You can do this by setting stderr to a file-like object or subprocess.PIPE:

```python import subprocess result = subprocess.run(['ls', '-l', '/nonexistent'], stderr=subprocess.PIPE, text=True) print(result.stderr) ```

Capturing Output with subprocess.Popen

The subprocess.Popen class allows more control over the process, including capturing output as it's produced. Here's how you can use it to capture output:

Python Remove Substring with Examples
Python Remove Substring with Examples

```python import subprocess process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) stdout, stderr = process.communicate() print(f'stdout:\n{stdout}') print(f'stderr:\n{stderr}') ```

Capturing Output Line by Line

In some cases, you might want to capture output line by line as it's produced. This can be achieved using a loop to read from the process's stdout or stderr:

the screenshoter is showing what to do with an animal and how to use it
the screenshoter is showing what to do with an animal and how to use it
Python output formatting cheat sheet
Python output formatting cheat sheet
a man holding up a poster with the words 5 levels of python on it
a man holding up a poster with the words 5 levels of python on it
Python testing techniques mocking and stubbing
Python testing techniques mocking and stubbing
a diagram showing how to use the python loop type for code blocking and data processing
a diagram showing how to use the python loop type for code blocking and data processing
DSA in Python for Beginners: Complete Visual Guide
DSA in Python for Beginners: Complete Visual Guide
an image of a computer screen with the text class tablet in purple and blue
an image of a computer screen with the text class tablet in purple and blue
three different types of python programming
three different types of python programming
the screenshoter is showing what to do with text and numbers on it's screen
the screenshoter is showing what to do with text and numbers on it's screen
an image of a screen with the text class and numbers in purple, blue, and red
an image of a screen with the text class and numbers in purple, blue, and red
All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)
Python Basics Cheat Sheet for Beginners | Learn Coding Step by Step
Python Basics Cheat Sheet for Beginners | Learn Coding Step by Step
CRUD Operations In Python With Source Code
CRUD Operations In Python With Source Code
How to Use the String join() Method in Python
How to Use the String join() Method in Python
Python
Python
Python Projects with Source Code (Beginner to Advanced)
Python Projects with Source Code (Beginner to Advanced)
Ultimate Python Cheat Sheet for Beginner
Ultimate Python Cheat Sheet for Beginner
Python operators infographic with cartoon elements
Python operators infographic with cartoon elements
Python Conditional Statements & Loops
Python Conditional Statements & Loops
an important python functions chart with the words and numbers on it, including instructions to use them
an important python functions chart with the words and numbers on it, including instructions to use them

```python import subprocess process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for line in process.stdout: print(line.strip()) for line in process.stderr: print(f'ERROR: {line.strip()}') ```

Best Practices and Pitfalls

When working with subprocess, there are a few best practices and pitfalls to keep in mind:

  • Always use capture_output=True or stdout/stderr arguments to capture output.
  • Be mindful of encoding issues. Using text=True can help, but it's not a silver bullet.
  • Don't forget to check the return code of the process. You can do this with result.returncode or process.wait().
  • Be careful when running commands with user-supplied input. This can be a security risk.

Conclusion

Capturing output from subprocesses in Python is a powerful technique that can be used in a wide variety of applications. Whether you're writing a script to automate a task, or building a tool that interacts with other software, the subprocess module is an invaluable resource. With a solid understanding of how to capture output, you're well on your way to becoming a Python subprocess master.