Sub topic 1
How a command-line program receives input and reports results
Prerequisites
This chapter assumes that you can write and run Python scripts, define functions, handle exceptions, and use a terminal shell. You should also know that python tool.py value runs a Python file with command-line arguments.
The command-line interface
A command-line interface (CLI) lets a user pass text to a program from a shell. Python exposes these words through sys.argv, a list whose first item is usually the script name.
A program reports through three standard streams:
stdoutcarries normal results.stderrcarries diagnostics and error messages.- An exit code is an integer status.
0conventionally means success; a nonzero value means failure.
The shell can redirect or combine these streams, so a tool should keep normal output and diagnostics separate.
Creating a parser and reading arguments
argparse.ArgumentParser is a standard-library object that defines the command syntax and converts the raw argument list into an object with named attributes. parse_args() reads sys.argv by default and validates the user’s input.
import argparse
import sys
def main(argv=None):
parser = argparse.ArgumentParser(
prog="greet",
description="Print a greeting."
)
parser.add_argument("name", help="who to greet")
parser.add_argument(
"-c", "--count", type=int, default=1,
help="number of greetings"
)
parser.add_argument(
"-v", "--verbose", action="store_true",
help="print diagnostics"
)
args = parser.parse_args(argv)
if args.verbose:
print(f"count={args.count}", file=sys.stderr)
for _ in range(args.count):
print(f"Hello, {args.name}!")
return 0
if __name__ == "__main__":
raise SystemExit(main())Passing argv explicitly makes main easy to call from tests. When argv is None, argparse reads the real command line.
Positional arguments
A positional argument is identified by its position. In the example, name is required, so python greet.py Ada stores "Ada" in args.name. Missing required positionals produce a usage message and exit code 2.
Options and flags
Options are named arguments such as --count. -c is a short alias. The type=int declaration converts the value and rejects non-integers. A boolean flag has no value: action="store_true" makes args.verbose false unless --verbose appears.
> callout note > Let argparse handle syntax errors. It writes a concise message to stderr, prints usage information, and exits with status 2.
Exercise
What does python greet.py Ada --count 2 --verbose write to stdout and stderr?
Show answer
stdout receives two greeting lines. stderr receives count=2. The program exits with code 0.