Sub topic 13
stdout, stderr, and stdin
This chapter assumes you can run a Python script, use print() and input(), and read basic try/except code. It also assumes you have a terminal where you can run shell commands.
The three standard streams
Every running program starts with three channels already open:
- stdin (standard input) carries data into the program. By default it is the keyboard.
- stdout (standard output) carries the program's normal results. By default it is the terminal.
- stderr (standard error) carries warnings and error messages. By default it also shows in the terminal.
Both output streams usually look the same on screen. The difference matters once a shell redirects them.
Choosing a stream
print() writes to sys.stdout unless you pass a different file argument. To write to stderr, pass sys.stderr:
import sys
print("Result: 42")
print("Warning: input file was empty", file=sys.stderr)Save this as report.py. The shell can now separate the two streams:
python report.py > out.txt
python report.py 2> err.txt
python report.py > out.txt 2> err.txtIn the first command, Result: 42 goes into out.txt and the warning still appears on screen. In the second, the reverse happens. The third sends each stream to its own file.
Use this rule: if another program or a file might consume the output, put it on stdout. Put everything meant for a human watching the run, such as progress, warnings, and errors, on stderr. That way python report.py > out.txt never mixes a warning into your data.
Reading from stdin
input() reads one line from stdin and strips the trailing newline. That works for prompts, but it is awkward for piped data. sys.stdin is a file-like object, so you can loop over it like a file and get one line per iteration:
import sys
total = 0
for line in sys.stdin:
line = line.strip()
if line:
total += int(line)
print(f"Total: {total}")Unlike input(), lines from sys.stdin keep their "\n", which is why the code calls strip(). The loop ends when stdin reaches end of file. You can feed this script from a pipe or a file:
printf "10\n20\n30\n" | python total.py
python total.py < numbers.txtOn a terminal, you signal end of input with Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows.
Common errors
- Mixed-up streams. Printing error messages with plain
print()puts them in redirected output files. Addfile=sys.stderr. - Buffering. Output to a pipe or file is buffered, so lines can appear late or in a different order from stderr. Pass
flush=Truetoprint()when timing matters. - Unexpected blank lines. Lines read from
sys.stdinstill contain a newline. Strip them before converting. - Blocking on input. A script that calls
input()while stdin is an empty terminal waits forever. When stdin is closed,input()raisesEOFError, so handle it in scripts meant for pipes.
Exercise
A script prints its computed answer with print(answer) and prints "Processing..." with print("Processing...", file=sys.stderr). You run python script.py > result.txt. What appears on screen, and what does result.txt contain?
Show answer
"Processing..." appears on screen because stderr is not redirected. result.txt contains only the answer, because > redirects stdout alone.
Exercise
Why does the stdin loop above call line.strip() before int(line), and what does the if line: check protect against?
Show answer
Lines from sys.stdin keep their trailing newline, so strip() removes it along with any surrounding spaces. The if line: check skips blank lines, which would otherwise make int("") raise a ValueError.