Multi-level argparse in Python (parsing commands like git)
21 Mar 2014
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.
I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.