Use this when giving Python scripts command-line options.
argparse
argparse builds command-line interfaces for Python scripts, defining arguments, options, types, defaults and help text, so scripts can be run with clear parameters like --host and --dry-run.
1. argparse builds CLIs with help, types and validation.
2. Use choices and required.
3. Subparsers for subcommands.
4. Return proper exit codes.
5. Alternatives: click, typer.
CLI args → argparse → validated namespace
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
The negative fixture should deliberately exercise risks such as environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs, choosing the cases most relevant to argument grammar, required/default/type/action semantics, help/error exit behavior and keeping CLI parsing separate from operation execution.
Step 2 Example Narrow the fault
import argparse
p = argparse.ArgumentParser()
p.add_argument("--site", required=True)
p.add_argument("--dry-run", action="store_true")
args = p.parse_args()
Step 3 Common mistakes Narrow the fault
- Reading
sys.argvby position. - No
choices=for fixed values.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- argparse defines arguments, options and help.
- Types and defaults validate input.
- --help is generated automatically.
python3 script.py --help— usage- argparse with types and choices — validation
- Subcommands — structure
ReferenceWhy it matters1 section · depth on demand
What it is
argparse builds command-line interfaces: options, types, defaults and help text, with validation before the script runs.
ReferenceImportant terms & boundaries2 sections · depth on demand
In depth
argparse turns a Python script into a proper command-line tool with named options, defaults, validation, help text and error messages. It makes scripts safer to run and easier for others to use.
import argparse
p = argparse.ArgumentParser(description="Deploy VLANs from NetBox")
p.add_argument("--site", required=True, help="site slug, e.g. oslo")
p.add_argument("--role", default="access-switch")
p.add_argument("--apply", action="store_true", help="make changes (default: dry run)")
p.add_argument("--workers", type=int, default=10, choices=range(1, 51), metavar="1-50")
p.add_argument("-v", "--verbose", action="count", default=0)
args = p.parse_args()
--help is generated automatically. Make dangerous actions explicit flags (--apply, --force) rather than defaults, and read secrets from environment variables, not command-line arguments (which appear in process lists and shell history).
Mechanics
The linked authority for bounded mechanics is Python Documentation — argparse; documentation support is separate from observed lab/production Evidence.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > argparse. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/library/argparse.html · confidence 94%Deep reference
Healthy vs suspicious evidence
Output interpretation
For argument grammar, required/default/type/action semantics, help/error exit behavior and keeping CLI parsing separate from operation execution, prefer typed fields and stable IDs over human presentation text.