โจ๏ธargparse: add_argument, subcommands, typesLESSON~15 min
Building CLIs with argparse
Python's argparse module is the standard library solution for parsing command-line arguments. It automatically generates help text, handles errors gracefully, and supports complex argument patterns without manual string parsing.
Why argparse Over sys.argv?
sys.argv gives you raw strings. argparse gives you typed, validated, documented arguments:
Creating a Parser
Positional Arguments
Positional arguments are required and identified by position (not a flag):
Optional Arguments (Flags)
Optional arguments use -- (long) or - (short) prefixes:
type= Parameter
The type= parameter validates and converts arguments:
choices= Parameter
Restrict values to a specific set:
nargs= โ Multiple Values
Subcommands (Subparsers)
Subcommands let you build tools like git commit, git push, docker run:
Usage:
Argument Groups
Organize arguments into logical groups for cleaner help output:
parse_known_args()
When you want to ignore unknown arguments (useful in testing or extensible tools):
Auto-Generated Help
argparse automatically creates -h/--help:
Putting It Together
Knowledge Check
What is the difference between positional and optional arguments in argparse?
What does `action='store_true'` do for an argument?
How do you add subcommands (like `git commit`, `git push`) using argparse?