Sub topic 1
How a Command-Line Program Receives Input and Reports Results
Every command-line tool you write with argparse sits on top of a small set of operating-system conventions. A program gets a list of argument strings, three standard data streams and an integer exit status. argparse automates the first of these and helps with the third. If you know all three, parser behavior stops looking arbitrary.
Prerequisites
This chapter assumes you can:
- write and run Python scripts, and define functions that raise and catch exceptions
- use a terminal shell (bash, zsh, PowerShell or similar) to run commands
- use pip and a virtual environment, which later chapters need for installation
You don't need to know argparse yet. This chapter doesn't use it.
The Working Model
When you type a command, the shell splits the line into words, starts a new process and hands it those words. The process reads input from its arguments and from standard input. It writes results to standard output and diagnostics to standard error. When it ends, it returns an exit status to the shell.
Each part of this model is a contract other programs rely on. Scripts, pipelines, cron jobs and CI systems all depend on it, so a tool that follows the conventions composes well with others.
Arguments Arrive as a List of Strings
Python exposes the arguments as sys.argv, a list of strings. Element 0 is the script name. The user's arguments follow.
import sys
print(sys.argv)Save this as show_args.py and run it:
python show_args.py hello "two words" --count 3['show_args.py', 'hello', 'two words', '--count', '3']Three details matter here:
- The shell does the splitting. Quotes group
two wordsinto one element before Python sees anything. Python never sees the quotes. - The shell also expands wildcards and variables. On POSIX shells,
*.txtbecomes a list of file names, and your program receives that list. - Everything is a string.
3is the text"3". Nothing insys.argvknows that--countis an option or that3is its value. Interpreting that structure is the job of a parser.
You could parse sys.argv by hand, but the edge cases add up quickly:
--count=3and--count 3both need to work.- Combined short flags such as
-vvneed splitting. - Missing values and unknown options need clear errors.
- Help text has to stay in sync with the code.
argparse handles these cases so you don't have to.
The Three Standard Streams
Every process starts with three open streams.
| Stream | Python object | File descriptor | Purpose |
|---|---|---|---|
| Standard input | `sys.stdin` | 0 | Data flowing into the program |
| Standard output | `sys.stdout` | 1 | The program's results |
| Standard error | `sys.stderr` | 2 | Errors, warnings, progress and diagnostics |
print() writes to sys.stdout by default. Pass file=sys.stderr to write to the error stream.
The split between stdout and stderr is what lets the shell redirect them independently:
python tool.py data.txt > result.txt 2> errors.log
python tool.py data.txt | sortIn the second command, only stdout enters the pipe. Warnings still appear on the terminal and don't corrupt the data that sort reads. If you print a warning to stdout, it ends up in the next program's input.
A practical rule is that stdout carries what a downstream program or file should receive, and stderr carries messages for the human at the terminal. Verbose logging, progress messages and error text all belong on stderr.
Reading from standard input
Many tools accept data from a pipe when no file is given. Iterating over sys.stdin yields lines lazily, so it works on large inputs:
import sys
total = 0
for line in sys.stdin:
total += 1
print(total)printf 'a\nb\nc\n' | python count_stdin.py3If you run this script in a terminal with no pipe, it waits for you to type input and finish with Ctrl-D (Ctrl-Z then Enter on Windows). A program that appears to hang is often waiting on stdin.
Buffering and encoding
When stdout is a terminal, Python flushes it line by line. When stdout is a pipe or file, Python buffers it in larger blocks. Output from print() and output from a subprocess can therefore appear out of order in a log. Use print(..., flush=True) for progress output that another process must see immediately.
Text streams also have an encoding that depends on the environment. Piping non-ASCII text on some systems, especially Windows, can raise UnicodeEncodeError. Pass encoding="utf-8" explicitly when you open files, as the example below does.
Exit Codes
The exit code is an integer the process returns to its parent. By convention:
0means success.- Any non-zero value means failure.
2is conventionally used for command-line usage errors.argparsefollows this convention.
The shell stores the last exit code in $? (bash and zsh) or $LASTEXITCODE (PowerShell). It uses the code in &&, || and if commands:
python tool.py data.txt && echo "worked" || echo "failed"On POSIX systems only the low 8 bits are kept, so valid codes run from 0 to 255. A code of 256 is reported as 0, which makes a failure look like success. Stick to small numbers.
Python gives you several ways to set the code:
| What happens | Exit code |
|---|---|
| Script ends normally | 0 |
| `sys.exit()` or `sys.exit(None)` | 0 |
| `sys.exit(3)` | 3 |
| `sys.exit("message")` | 1, and the message is printed to stderr |
| Uncaught exception | 1, with a traceback on stderr |
| Ctrl-C (`KeyboardInterrupt`) at the terminal | Usually reported by the shell as 130 |
sys.exit() works by raising SystemExit. Code that catches a bare except: or except BaseException: will swallow it, which is one more reason to catch specific exception types.
A Small Complete Example
This tool counts lines in a file. It uses no argparse, only the model above. It takes an optional argument list and returns the exit code instead of calling sys.exit itself, a structure that a later chapter develops fully.
import sys
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
if len(argv) != 1:
print("usage: wc_lines.py FILE", file=sys.stderr)
return 2
try:
with open(argv[0], encoding="utf-8") as handle:
count = sum(1 for _ in handle)
except OSError as exc:
print(f"wc_lines.py: {exc}", file=sys.stderr)
return 1
print(count)
return 0
if __name__ == "__main__":
raise SystemExit(main())Try the three outcomes:
python wc_lines.py notes.txt; echo "exit=$?"
python wc_lines.py missing.txt; echo "exit=$?"
python wc_lines.py; echo "exit=$?"42
exit=0
wc_lines.py: [Errno 2] No such file or directory: 'missing.txt'
exit=1
usage: wc_lines.py FILE
exit=2The result (42) goes to stdout. Both error messages go to stderr. The codes separate a runtime failure (1) from misuse (2). The 42 assumes notes.txt has 42 lines.
Common Errors
- Treating arguments as typed values.
sys.argv[1] + 1raisesTypeErrorbecause the element is a string. Convert withint()and handleValueError. - Printing errors to stdout. The message then flows into pipes and redirected files. Use
file=sys.stderr. - Returning success after a failure. If you catch an exception, print a message and fall off the end of the script, the exit code is 0. Callers and CI cannot detect the failure.
- Running logic at import time. Code outside a function or an
if __name__ == "__main__":guard runs whenever the module is imported, including from tests. Put the work inmain. - Calling
sys.exitdeep inside helper functions. This makes code hard to test and reuse. Raise exceptions in helpers and convert them to exit codes in one place. - Assuming a terminal. Output may go to a pipe or file, so don't depend on cursor control, colors or interactive prompts without checking
sys.stdout.isatty(). - Using exit codes above 255. They wrap around on POSIX systems.
Where argparse Fits
argparse takes over the first step of the model. It reads sys.argv, applies your declared rules, converts strings to typed values, and produces help text. When it rejects the input, it follows the stream and exit-code conventions from this chapter. It writes a usage message and error to stderr and exits with status 2. The next chapters build on that behavior.
Exercise
A script prints a progress message with print("Processing...") and then prints its result with print(total). A user runs python tool.py data.txt > out.txt and finds "Processing..." inside out.txt. What should change, and why?
Show answer
Send the progress message to stderr with print("Processing...", file=sys.stderr). The > redirect captures only stdout, so with the change out.txt would contain just the result while the progress message still shows on the terminal.
Exercise
A script catches FileNotFoundError, prints "file not found" to stderr, and then ends without calling sys.exit or returning a code. What exit code does the shell see, and why is that a problem?
Show answer
The exit code is 0, because the script ended normally. The shell, && chains and CI systems treat the run as a success even though it failed. The handler should make the program exit with a non-zero code, such as 1, either by returning it from main or by calling sys.exit(1).