0Pricing
Python Academy · Lesson

Capturing Output

Read stdout and stderr.

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))

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