Multi-level argparse in Python (parsing commands like git)
It’s a common pattern for command line tools to have multiple subcommands that run off of a single executable. For example, git fetch origin and git commit --amend both use the same executable /usr/bin/git to run. Each subcommand has its own set of required and optional parameters.
This pattern is fairly easy to implement in your own Python command-line utilities using argparse. Here is a script that pretends to be git and provides the above two commands and arguments.
The argparse library gives you all kinds of great stuff. You can run ./git.py --help and get the following:
You can get help on a particular subcommand with ./git.py commit --help.
Want bash completion on your awesome new command line utlity? Try argcomplete, a drop in bash completion for Python + argparse.