0Pricing
Python Academy · Lesson

Capturing Output

Read stdout and stderr.

Capturing Output is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Capturing stdout

To read what a command prints, pass capture_output=True. The text appears in the result's stdout attribute.

import subprocess

cp = subprocess.run(['echo', 'hello'], capture_output=True)
print(cp.stdout)

Bytes vs Text

By default output is bytes. Pass text=True to get decoded strings instead, which is usually what you want.

import subprocess

cp = subprocess.run(['echo', 'hello'], capture_output=True, text=True)
print(repr(cp.stdout))

Stripping Trailing Newline

Command output often ends in a newline. Use .strip() to clean it up before using the value.

import subprocess

cp = subprocess.run(['echo', 'value'], capture_output=True, text=True)
clean = cp.stdout.strip()
print('[' + clean + ']')

Capturing stderr

Errors usually go to stderr, captured separately. This keeps normal output and error messages distinct.

import subprocess

cp = subprocess.run(['ls', '/no/such/dir'], capture_output=True, text=True)
print('stdout:', repr(cp.stdout))
print('stderr:', cp.stderr.strip())

Using the Output in Code

Captured output is just a string, so you can parse it: split lines, convert numbers, or feed it into the rest of your program.

import subprocess

cp = subprocess.run(['printf', 'a\nb\nc\n'], capture_output=True, text=True)
lines = cp.stdout.splitlines()
print('line count:', len(lines))
print(lines)

Redirecting stderr to stdout

To merge error output into the normal stream, set stderr=subprocess.STDOUT. Both then appear in stdout.

import subprocess

cp = subprocess.run(['ls', '/no/such/dir'], stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT, text=True)
print(cp.stdout.strip())

Providing Input

Feed data to a command's stdin with the input argument. Here we pipe text into cat.

import subprocess

cp = subprocess.run(['cat'], input='piped in\n', capture_output=True, text=True)
print(cp.stdout.strip())

check_output Shortcut

subprocess.check_output() runs a command and returns its stdout directly, raising on failure. It is a convenient one-liner for capturing.

import subprocess

out = subprocess.check_output(['echo', 'quick'], text=True)
print(out.strip())

Discarding Output

To silence a command, redirect its streams to subprocess.DEVNULL.

import subprocess

cp = subprocess.run(['echo', 'silent'], stdout=subprocess.DEVNULL)
print('return code only:', cp.returncode)

Handling Errors With Output

When using check=True, the raised CalledProcessError still carries the captured output and stderr for diagnosis.

import subprocess

try:
    subprocess.run(['ls', '/missing'], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
    print('failed:', e.returncode)
    print('stderr:', e.stderr.strip())

Putting It Together

A typical helper runs a command, checks success, and returns clean text. This wraps the common pattern.

import subprocess

def capture(cmd):
    cp = subprocess.run(cmd, capture_output=True, text=True, check=True)
    return cp.stdout.strip()

print(capture(['echo', 'final result']))

Quick Check

Test your understanding of capturing output.

Recap

You learned to capture output:

  • capture_output=True plus text=True gives string stdout and stderr.
  • Merge streams with stderr=subprocess.STDOUT; silence with DEVNULL.
  • Feed input via input=; check_output is a shortcut.
  • Errors carry captured output for debugging.

Next: reading environment variables and the os module.

Frequently asked questions

Is the “Capturing Output” lesson free?

Yes — the full text of “Capturing Output” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Capturing Output”?

Read stdout and stderr. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Capturing Output” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Running Commands with subprocess
  2. Capturing Output
  3. Environment and os Module
  4. shutil for File Operations
← Back to Python Academy