Sub topic 4
Capturing output as text or bytes
This chapter assumes you can call subprocess.run with an argument list and know that a process has separate standard output (stdout) and standard error (stderr) streams. It also assumes you know the difference between bytes and str.
What capture_output does
By default, a child process writes to the same terminal as your program. Your program never sees that output. To receive it, ask run to connect pipes to the child's streams. capture_output=True is shorthand for stdout=subprocess.PIPE, stderr=subprocess.PIPE. The captured data appears on the returned CompletedProcess as result.stdout and result.stderr.
import subprocess
import sys
code = "import sys; print('out'); print('err', file=sys.stderr)"
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
)
print(repr(result.stdout))
print(repr(result.stderr))This prints 'out\n' and 'err\n'. The two streams stay separate.
Bytes by default, text on request
Without extra arguments, the captured values are bytes. A pipe carries raw bytes, and Python does not guess how to decode them. Set text=True to get str instead. Python then decodes the output and converts line endings (\r\n becomes \n).
With text=True, Python decodes with your locale's preferred encoding. That encoding differs between machines, especially on Windows. For predictable results, name the encoding yourself.
import subprocess
import sys
code = "import sys; sys.stdout.buffer.write(b'caf\\xc3\\xa9\\n')"
raw = subprocess.run([sys.executable, "-c", code], capture_output=True)
print(raw.stdout)
decoded = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
encoding="utf-8",
errors="replace",
)
print(decoded.stdout.strip())Passing encoding turns on text mode, so you don't need text=True as well. The errors="replace" argument substitutes a replacement character for invalid bytes instead of raising UnicodeDecodeError. Keep the default bytes when the output is binary, such as an image or a compressed archive.
Choosing where each stream goes
You can set stdout and stderr separately.
| Setting | Effect |
|---|---|
| `subprocess.PIPE` | Capture the stream into the result |
| `subprocess.DEVNULL` | Discard the stream |
| `subprocess.STDOUT` (stderr only) | Send stderr into the stdout pipe |
| Not set | Inherit the parent's stream, so it prints to your terminal |
Merging with stderr=subprocess.STDOUT is useful when you want one log in the order the child wrote it. In that case result.stderr is None.
Common errors
result.stdoutisNone. You did not pipe that stream. Addcapture_output=Trueorstdout=subprocess.PIPE.- Mixing
strandbytes. Without text mode,"ok" in result.stdoutraisesTypeError. Compare againstb"ok"or enable text mode. capture_outputwithstdoutorstderr. Python raisesValueError. Use one style or the other.- Decoding errors. Set
encodinganderrorsexplicitly instead of relying on the locale. - Trailing newline. Most commands end output with
\n. Use.strip()or.splitlines()before comparing.
run waits for the child to finish and holds all output in memory. That works for modest output. For very large output, or output you want to process while the child is still running, you need Popen, covered later.
Exercise
You run subprocess.run(["ls", "missing"], capture_output=True, text=True) and the directory does not exist. Where does the error message from ls appear, and how would you get it in the same string as normal output?
Show answer
The message appears in result.stderr, because stderr is captured separately from stdout. To combine them, replace capture_output=True with stdout=subprocess.PIPE, stderr=subprocess.STDOUT. Everything then arrives in result.stdout, and result.stderr is None.