Lesson 3 of 9 · 20m
stdout, stderr, Exit Codes, and Machine Output
Professional tools separate results from diagnostics, honor exit status, and make automation safe with stable machine-readable output.
A CLI is not successful because it printed something. It is successful because another program can depend on what it printed and whether it failed. I have watched backup jobs report success for months because a tool printed ERROR and then exited zero. Output discipline is operational discipline.
Results go to stdout; diagnostics go to stderr
import json
import sys
def emit_report(report, json_output):
if json_output:
json.dump(report, sys.stdout, indent=2)
sys.stdout.write("
")
else:
sys.stdout.write(f"scanned={report['scanned']} failed={report['failed']}
")
def warn(message):
print(f"warning: {message}", file=sys.stderr)This separation lets a user run tool --json > report.json while still seeing warnings on the terminal. If you print both data and chatter to stdout, every consumer has to parse your prose.
Exit codes are the real boolean API
Use a small, documented set:
0 success
1 runtime failure
2 invalid command-line usage
3 configuration error
4 resource or permission errorDo not invent forty codes unless you are building a platform utility with a published interface. But do preserve the distinction between “the command was nonsense” and “the command ran and the target system failed.” sys.exit(main()) keeps the mapping explicit.
Text output is for humans; JSON is a compatibility promise
Human output can be aligned, colored, and reworded. JSON output cannot change casually because someone has jq pipelines depending on it. Emit complete objects even when lists are empty:
{"version": 1, "summary": {"scanned": 12, "failed": 0}, "items": []}A top-level version field gives you room to evolve shape later. Never print Python dict reprs and call it JSON; single quotes and None are not a wire format.
Respect pipes and non-terminals
When stdout is piped, disable color and decorative spinners. When output is a terminal, human formatting is fine. Libraries usually expose sys.stdout.isatty(), but use it to select presentation — not to change what the command actually does.
Field notes
- Write newline-terminated output. Many Unix tools mishandle final lines without
. - If a command creates a file, print the path to stdout and progress to stderr; shell capture then does the obvious thing.
--quietshould reduce diagnostics, never hide a failure or alter the exit code.- Catch expected operational exceptions and print concise errors. A traceback is useful for bugs, hostile for mistyped credentials.
Was this lesson helpful?