Sub topic 13
stdout, stderr, and stdin
This chapter covers the three standard streams that every Python process starts with, how print() and input() use them, and how a shell can connect them to files and other programs. It assumes you can run a Python script, know str, int and float, and can read a basic try/except. You should also know print() and input() from earlier chapters.
What the standard streams are
When the operating system starts a process, it gives that process three open channels for text:
- stdin (standard input) is where the program reads input. By default it is connected to the keyboard.
- stdout (standard output) is where the program writes its normal results. By default it is connected to the terminal.
- stderr (standard error) is where the program writes diagnostics, such as warnings and error messages. By default it also goes to the terminal.
Because stdout and stderr both appear on the terminal, they look the same when you run a script by hand. They are separate channels, though, and a shell can send them to different places.
Python exposes the streams as file-like objects in the sys module: sys.stdin, sys.stdout and sys.stderr. They are text streams, so they read and write str values.
How print() and input() use the streams
print() writes to sys.stdout unless you pass a different file argument. input() reads one line from sys.stdin. If you pass a prompt to input(), the prompt is written to stdout (in the usual interactive case) before the read.
So these two lines are almost equivalent:
import sys
print("hello")
sys.stdout.write("hello\n")The differences are that print() adds the end string for you and converts its arguments with str(). sys.stdout.write() accepts only a string and does not add a newline.
Writing to stderr
Pass file=sys.stderr to print() to send a message to the error stream:
import sys
print("Result: 42")
print("Warning: input file was empty", file=sys.stderr)Run it normally and both lines show up in the terminal. Now redirect stdout to a file in a POSIX shell:
# Shell commands, shown here as comments:
# python report.py > out.txt # "Result: 42" goes to out.txt, the warning still shows on screen
# python report.py 2> err.txt # the warning goes to err.txt, the result still shows on screen
# python report.py > out.txt 2>&1 # both streams go to out.txtThe number before > is the stream's file descriptor: 0 is stdin, 1 is stdout and 2 is stderr. > alone means 1>.
This separation is the reason to use stderr. If a script's real output is piped into another program, a warning on stdout would corrupt the data the next program receives. A warning on stderr stays visible to the person at the terminal and leaves the data clean.
| Stream | File descriptor | Python object | Typical content |
|---|---|---|---|
| stdin | 0 | `sys.stdin` | Data typed or piped in |
| stdout | 1 | `sys.stdout` | Results, the program's real output |
| stderr | 2 | `sys.stderr` | Warnings, errors, progress messages |
Reading all of stdin
input() reads one line at a time and strips the trailing newline. When stdin is a pipe or a redirected file, you often want to process every line. Iterate over sys.stdin, just as you iterate over a file object:
import sys
total = 0
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
total += float(line)
except ValueError:
print(f"Skipping {line!r}: not a number", file=sys.stderr)
print(f"Sum: {total:.2f}")Save this as sum.py and run it with piped data:
# Shell commands, shown here as comments:
# printf '10\n20.5\nabc\n5\n' | python sum.py
# stdout: Sum: 35.50
# stderr: Skipping 'abc': not a numberThe bad line is reported on stderr, so python sum.py < numbers.txt > total.txt would put only the sum in total.txt.
Other ways to read stdin:
sys.stdin.readline()reads one line and keeps the trailing"\n".sys.stdin.read()reads everything until end of input and returns one string.sys.stdin.readlines()returns a list of lines.
Unlike sys.stdin.readline(), input() removes the newline and raises EOFError at end of input. readline() returns an empty string instead.
End of input and EOFError
When stdin is a keyboard, the user can signal end of input with Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows. When stdin is a pipe or file, end of input happens when the data runs out.
A program that calls input() in a loop must handle this case, or it crashes with a traceback when the input ends:
lines = []
while True:
try:
line = input()
except EOFError:
break
lines.append(line)
print(f"Read {len(lines)} lines")This loop works the same whether a person types lines or the shell pipes a file in.
Buffering and flushing
Writing to a stream is usually buffered: Python collects output in memory and writes it out in larger chunks, because that is faster than many small writes. The rules depend on where the stream goes:
- If stdout is a terminal, it is line-buffered. Output appears when a newline is written.
- If stdout is a pipe or a file, it is block-buffered. Output appears when the buffer fills or the program exits.
- stderr is written promptly, so error messages are not lost if the program crashes.
This explains a common surprise. A prompt without a newline may not appear before input() waits, and a progress message may not appear until much later when output is piped. Use flush=True to force the buffer out:
import time
print("Working", end="", flush=True)
for _ in range(3):
time.sleep(1)
print(".", end="", flush=True)
print(" done")Without flush=True, the terminal may show nothing for three seconds, because no newline has been printed yet and the text is still waiting in the buffer. You can also call sys.stdout.flush() directly. The input() function flushes stdout for you before it reads, so ordinary prompts work without extra effort.
Interleaving of stdout and stderr
Because the two streams are buffered differently, their output can appear in a different order from the order of your print() calls when both are sent to the same file or pipe. For example, in python script.py > all.txt 2>&1, the stderr lines may appear before stdout lines that were printed earlier, because stdout is block-buffered and stderr is not. If order matters, pass flush=True on the stdout prints, or run with -u.
Redirecting streams inside a program
You can change where print() writes without editing every call. The standard library provides contextlib.redirect_stdout and contextlib.redirect_stderr, which swap the stream for the duration of a with block:
import io
from contextlib import redirect_stdout
buffer = io.StringIO()
with redirect_stdout(buffer):
print("captured")
print("also captured")
print(f"Captured text: {buffer.getvalue()!r}")The output is Captured text: 'captured\nalso captured\n'. This is useful in tests, where you want to check what a function prints, and when you call code that prints more than you want to show.
io.StringIO is an in-memory text stream. It supports the same write() and read() methods as a file, so it also works as the file= argument of print().
Assigning sys.stdout = something also works, but you must restore it yourself, and an exception between the two steps can leave it broken. Prefer the context managers.
Detecting whether a stream is a terminal
A program sometimes behaves differently for a person and for a pipe: it might show a prompt, use colors, or print a progress bar only when a human is watching. Use isatty():
import sys
if sys.stdin.isatty():
name = input("Your name: ")
else:
name = sys.stdin.readline().strip()
print(f"Hello, {name}!")isatty() returns True when the stream is connected to a terminal and False when it is a pipe or file. Checking sys.stdout.isatty() before writing color codes keeps escape sequences out of saved output.
Exit codes and stderr
Streams carry text. The exit code carries success or failure to the shell. A script that reports an error on stderr should usually also exit with a non-zero status, so callers can detect the failure without parsing text:
import sys
def main() -> int:
try:
count = int(sys.argv[1])
except (IndexError, ValueError):
print("usage: python repeat.py COUNT", file=sys.stderr)
return 2
print("hi\n" * count, end="")
return 0
if __name__ == "__main__":
sys.exit(main())sys.exit(0) means success. Any other number means failure. By convention, 2 means incorrect usage of a command and 1 means a general error.
Common errors
- Sending errors to stdout. The message ends up in the saved output or the next program's input. Use
file=sys.stderr. - Expecting prompt text to appear immediately when piped. Output is block-buffered. Use
flush=Trueor-u. - Forgetting
EOFError.input()raises it when there is no more input, for example when a script is run with stdin closed or redirected from an empty file. - Leaving
sys.stdoutreassigned. Useredirect_stdoutso the original stream is restored. - Mixing
read()and iteration on the same stream without care. Pick one reading style for a given stream so lines are not skipped or read twice. - Treating a closed stream as normal. If the next program in a pipe exits early (for example
python big.py | head -1), writing to stdout can raiseBrokenPipeError. Command-line tools often catch it and exit quietly.
Exercise
A script prints its results with print() and its warnings with print(..., file=sys.stderr). You run python tool.py > results.txt. Where does each kind of message go, and what changes if you run python tool.py > results.txt 2>&1?
Show answer
With > results.txt, the results go to the file and the warnings still appear on the terminal, because only stdout (descriptor 1) was redirected. With > results.txt 2>&1, stderr (descriptor 2) is redirected to wherever stdout points, so both results and warnings are written to results.txt. Because stdout is block-buffered when redirected and stderr is not, the warnings may appear in the file out of order relative to the results unless you flush stdout or run with -u.
Exercise
Write a loop that reads lines with input() until end of input, and prints how many non-empty lines were read. What must it handle so it works with piped data?
Show answer
It must catch EOFError, which input() raises when stdin has no more data. count = 0 while True: try: line = input() except EOFError: break if line.strip(): count += 1 print(count)