Sub topic 4
Capturing output as text or bytes
This chapter assumes you can call subprocess.run and read a CompletedProcess. It also assumes you know what standard output and standard error are, and how Python's str differs from bytes. It covers how to get a child process's output into your program, what type that output has, and where decoding goes wrong.
Output is not captured unless you ask
By default, a child process inherits your program's standard streams. Its output goes to your terminal, not to your program. In that case result.stdout and result.stderr are None.
To capture output, redirect the streams into pipes. The shortcut is capture_output=True. It is equivalent to passing stdout=subprocess.PIPE and stderr=subprocess.PIPE.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; sys.stdout.buffer.write('héllo\\n'.encode('utf-8'))"],
capture_output=True,
)
print(type(result.stdout))
print(result.stdout)
print(result.stderr)This prints <class 'bytes'>, then b'h\xc3\xa9llo\n', then b''. Without a text option, you always get bytes. An empty stream gives b'', not None.
Choosing text or bytes
Pass text=True to get str. The older spelling universal_newlines=True does the same thing. Passing encoding or errors also switches to text mode.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import sys; sys.stdout.buffer.write('héllo\\n'.encode('utf-8'))"],
capture_output=True,
text=True,
encoding="utf-8",
)
print(repr(result.stdout))This prints 'héllo\n'.
| Option | Effect |
|---|---|
| none of the text options | `stdout` and `stderr` are `bytes` |
| `text=True` | Decodes with the locale's preferred encoding |
| `encoding="utf-8"` | Decodes with the encoding you name, and implies text mode |
| `errors="replace"` | Chooses what happens to undecodable bytes, and implies text mode |
The decoding side of text=True also applies to input. In text mode you pass input as a str. In bytes mode you pass bytes. Mixing them raises TypeError.
Always name the encoding
With text=True alone, Python decodes using locale.getpreferredencoding(False). That is usually UTF-8 on Linux and macOS. On Windows it is often a legacy code page such as cp1252. The same script can then decode the same bytes differently on two machines.
Set encoding explicitly when you know what the child writes. If the child's output depends on its own locale, you may also need to set that in the child's environment.
Newline translation in text mode
Text mode applies universal newlines. The sequences \r\n and \r in the child's output become \n.
import subprocess
import sys
code = "import sys; sys.stdout.buffer.write(b'a\\r\\nb\\r\\n')"
as_text = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
as_bytes = subprocess.run([sys.executable, "-c", code], capture_output=True)
print(repr(as_text.stdout))
print(repr(as_bytes.stdout))This prints 'a\nb\n' and then b'a\r\nb\r\n'. If you need the exact bytes, for example to compute a checksum or compare against a file, stay in bytes mode.
Handling bytes that do not decode
Not every program writes valid text. A program may print a file name in a legacy encoding, or its output may be binary. With the default errors="strict", a bad byte raises UnicodeDecodeError after the process has already finished. You lose the result.
import subprocess
import sys
code = "import sys; sys.stdout.buffer.write(b'ok \\xff\\n')"
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
encoding="utf-8",
errors="replace",
)
print(repr(result.stdout))This prints 'ok \ufffd\n'. The invalid byte 0xff became the replacement character U+FFFD. Other handlers exist. errors="backslashreplace" keeps a visible trace such as \xff, and errors="ignore" drops the byte silently.
Use replace or backslashreplace for logging and display. Do not use them when you must preserve the data. If the output can contain arbitrary bytes, capture bytes and decode only the parts you know are text.
Binary output
Some commands produce binary data, such as an image converter, a compressor or git cat-file. Capture these as bytes and never set a text option.
import subprocess
import sys
code = "import sys; sys.stdout.buffer.write(bytes(range(256)))"
result = subprocess.run([sys.executable, "-c", code], capture_output=True)
print(len(result.stdout), result.stdout[:4])This prints 256 b'\x00\x01\x02\x03'. Text mode would fail on this data, and newline translation would also corrupt it.
Separate and merged streams
By default, stdout and stderr are separate attributes. Often you want diagnostics and normal output in one stream, in the order they were written. Redirect stderr into stdout:
import subprocess
import sys
code = (
"import sys; "
"print('to stdout', flush=True); "
"print('to stderr', file=sys.stderr, flush=True)"
)
result = subprocess.run(
[sys.executable, "-c", code],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
)
print(result.stdout)
print(result.stderr)Both lines appear in result.stdout, and result.stderr is None. The flush=True calls matter. A child that buffers its streams separately can still emit them in a different order than it wrote them.
Do not combine capture_output=True with an explicit stdout= or stderr=. run raises ValueError, because capture_output already sets both.
To discard a stream, use subprocess.DEVNULL. This is cheaper than capturing output you will not read, and it removes any chance of a full pipe blocking the child.
import subprocess
import sys
subprocess.run(
[sys.executable, "-c", "print('noise')"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)The following diagram summarizes where each stream goes under each option.
Captured output on failure
With check=True, a non-zero exit raises CalledProcessError. If you captured the streams, the exception carries them, so you can put the child's own error message in your log.
import subprocess
import sys
code = "import sys; print('partial'); print('bad input', file=sys.stderr); sys.exit(2)"
try:
subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
encoding="utf-8",
check=True,
)
except subprocess.CalledProcessError as exc:
print("code:", exc.returncode)
print("stdout:", exc.stdout.strip())
print("stderr:", exc.stderr.strip())The exception's output attribute is an alias of stdout. A TimeoutExpired exception also carries whatever output arrived before the deadline. That partial output may be bytes even when you requested text, so decode it yourself before you use it.
Memory limits and large output
run reads all output into memory before it returns. That is fine for a command that prints a few kilobytes. It is a problem for a command that prints gigabytes, such as a database dump or a verbose build.
For large output, you have two options:
- Redirect to a file by passing an open file object, for example
stdout=open_file. The data goes straight to disk and never enters your process. - Use
Popenand read the stream incrementally. A later chapter covers this.
Common mistakes
- Reading
result.stdoutwithout capturing. It isNone, soresult.stdout.strip()raisesAttributeError. - Forgetting that the type depends on the options. Code that works with
text=Truebreaks when someone removes it, becausebytes.strip()returns bytes and comparisons tostrsilently fail. - Relying on the locale. Decoding that works on your machine fails on a CI runner with a different locale.
- Assuming stream order. Separate pipes carry no ordering between them. Merge with
stderr=subprocess.STDOUTif order matters. - Parsing human-oriented output. Prefer a machine-readable flag such as
--porcelainor--jsonwhen the program offers one.
Exercise
A command prints a file name that contains the byte 0xE9 (Latin-1 for "é"), then exits with status 1. You call subprocess.run(cmd, capture_output=True, encoding="utf-8", check=True). What happens, and how do you fix it so you can log the output?
Show answer
With strict decoding, the 0xE9 byte is not valid UTF-8, so Python raises UnicodeDecodeError while reading the output, before check=True can raise CalledProcessError. You lose both the output and the exit status. Either set encoding="latin-1" if you know the child's encoding, or add errors="replace" (or "backslashreplace") so decoding always succeeds. Then check=True raises CalledProcessError, and exc.stdout holds the decoded text for your log.
Exercise
You want one string containing a program's normal output and its error messages, in the order they were written. Which arguments do you pass to subprocess.run, and why might the order still be wrong?
Show answer
Pass stdout=subprocess.PIPE, stderr=subprocess.STDOUT and a text option such as text=True with an explicit encoding. Then read result.stdout. The order can still be wrong if the child buffers its own streams separately and flushes them at different times. Flushing in the child, or running a Python child with -u, fixes this.