Command-Line Programs with argparse
Scenario: A backup script's positional inputs are easy to reverse and impossible to discover.
New words, in plain English
- CLI - command-line interface
- Argument parser - code validating and documenting command-line options
- Exit code - zero for success and nonzero for failure
- Environment variable - a named value supplied by the process environment
argparse produces help, validates types, and supports required flags, choices, defaults, and subcommands. Keep secrets out of arguments because process listings may expose them; use protected environment variables or files.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
import argparse
parser = argparse.ArgumentParser(description="Check a service")
parser.add_argument("--port", type=int, required=True)
parser.add_argument("--env", choices=["dev", "prod"], default="dev")
args = parser.parse_args()
Tip: Return meaningful exit codes so shell scripts and CI can trust the tool.
Goal: Practice this idea in the py-argparse-cli challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.