Sub topic 12
Building Tools with Subcommands
Tools such as git commit, pip install and docker run use subcommands. One program offers several actions, and each action has its own arguments. This chapter assumes you can build a parser with positional arguments, options and flags, and that you have a main(argv) function that returns an exit code. It shows how add_subparsers splits a tool into commands, how to dispatch to the right function, and which mistakes to expect.
How subcommands parse
A subcommand is a word that selects a separate parser. The top-level parser reads its own options, then hands everything after the subcommand word to the parser registered under that word.
Each subparser is a full ArgumentParser. It has its own arguments, its own -h output and its own validation. This also means options are scoped. An option exists only at the level where you declared it.
Creating subparsers
Call add_subparsers() once on the parent parser. Then call add_parser(name) on the object it returns, once per command.
import argparse
import sys
def cmd_add(args):
if args.verbose:
print(f"[verbose] adding {args.item!r}", file=sys.stderr)
print(f"added {args.item}")
return 0
def cmd_list(args):
print("listing", "all" if args.all else "open", "items")
return 0
def build_parser():
parser = argparse.ArgumentParser(prog="todo", description="A tiny todo manager.")
parser.add_argument("-v", "--verbose", action="store_true",
help="print extra information to stderr")
sub = parser.add_subparsers(
dest="command", required=True, metavar="COMMAND", title="commands"
)
add = sub.add_parser("add", help="add an item",
description="Add an item to the todo list.")
add.add_argument("item", help="text of the item")
add.set_defaults(func=cmd_add)
ls = sub.add_parser("list", aliases=["ls"], help="list items")
ls.add_argument("--all", action="store_true", help="include finished items")
ls.set_defaults(func=cmd_list)
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
return args.func(args)
if __name__ == "__main__":
raise SystemExit(main())The parameters of add_subparsers that matter in practice:
| Parameter | Effect |
|---|---|
| `dest` | Name of the namespace attribute that stores which command was used. |
| `required` | If `True`, omitting the command is an error. The default is `False`. |
| `metavar` | Text shown in usage and error messages in place of the `{add,list}` choice list. |
| `title` | Gives the command list its own section in the `-h` output. |
The parameters of add_parser:
| Parameter | Effect |
|---|---|
| `help` | One-line text shown in the parent's command list. |
| `description` | Longer text shown in the subcommand's own `-h` output. |
| `aliases` | Extra names for the same command, such as `ls` for `list`. |
A subcommand created without help= still works, but it does not appear in the parent's command list.
Dispatching with set_defaults
set_defaults(func=cmd_add) stores the handler in the namespace whenever that subparser runs. Afterwards main needs no if/elif chain. It calls args.func(args) and returns the result as the exit code. The handlers are ordinary functions that take a namespace. You can test them without building a parser.
There is an alternative. Keep a dictionary such as {"add": cmd_add, "list": cmd_list} and look up args.command. This keeps the parser definition free of references to handlers, but you must update the dictionary whenever you add a command. Aliases make it worse, because args.command holds whichever name the user typed, so ls needs its own entry. For most tools set_defaults is simpler, and it handles aliases for free.
Running it
Save the script as todo.py and try these calls.
$ python todo.py add milk
added milk
$ python todo.py -v add milk
[verbose] adding 'milk'
added milk
$ python todo.py ls --all
listing all items
$ python todo.py
usage: todo [-h] [-v] COMMAND ...
todo: error: the following arguments are required: COMMANDThe program exits with status 2 in the last case. This is the same status argparse uses for every usage error.
Options belong to one level
The third form below looks reasonable but fails.
$ python todo.py add milk -v
usage: todo [-h] [-v] COMMAND ...
todo: error: unrecognized arguments: -vThe add subparser has no -v, so it leaves the token unparsed. The top-level parser has already finished with its own options, so it reports the leftover as an error. -v must appear before the command word: todo -v add milk.
You have three ways to handle this:
- Accept the rule. This is how
git -C path commitworks. Global options go before the command, and command options go after it. - Declare the option on every subparser that needs it. Parent parsers make this easy, and a later chapter covers them.
- Document the placement in the
epilogof the top-level parser.
Avoid using the same dest at both levels, for example --verbose on the parent and on a subparser. Which value ends up in the namespace depends on the Python version. Use different names, or declare the option at one level only.
Optional commands and default behaviour
Sometimes a tool should do something useful when no command is given. In that case, leave required off and set the fallback on the top-level parser.
import argparse
def cmd_status(args):
print("status: ok")
return 0
def cmd_reset(args):
print("reset done")
return 0
parser = argparse.ArgumentParser(prog="svc")
sub = parser.add_subparsers(dest="command")
sub.add_parser("status").set_defaults(func=cmd_status)
sub.add_parser("reset").set_defaults(func=cmd_reset)
parser.set_defaults(func=cmd_status)
args = parser.parse_args([])
raise SystemExit(args.func(args))Running svc with no arguments now behaves like svc status. A default set on the parser applies unless a subparser sets its own value for the same name. When a subcommand is given, its value wins.
Nested subcommands
A subparser can have subparsers of its own, which gives you commands such as tool remote add. Call add_subparsers on the subparser, and give each level a different dest. If two levels share a dest, the inner value overwrites the outer one.
import argparse
parser = argparse.ArgumentParser(prog="tool")
top = parser.add_subparsers(dest="command", required=True)
remote = top.add_parser("remote", help="manage remotes")
remote_sub = remote.add_subparsers(dest="remote_command", required=True)
remote_add = remote_sub.add_parser("add", help="add a remote")
remote_add.add_argument("url")
args = parser.parse_args(["remote", "add", "https://example.com"])
print(args.command, args.remote_command, args.url)This prints remote add https://example.com. Keep nesting to two levels. Deeper trees are hard for users to remember and hard to maintain.
Common errors
AttributeError: 'Namespace' object has no attribute 'func'. The command was optional and the user left it out, or you forgotset_defaultson one subparser. Userequired=Trueand give every subparser afunc.- Help for a command is missing from the parent's list. You omitted
help=inadd_parser. - An option works for one command and is rejected for another. Options are scoped to the parser where you declared them. Check which parser received the
add_argumentcall. - Wrong attribute read inside a handler. A handler for
addcannot readargs.all, because--allbelongs tolist. Handlers should read only the arguments their own subparser declared, plus any deliberate global options. args.commandislsinstead oflist. With aliases,deststores the name the user typed. Dispatch onfunc, not on the name.
Testing works the same way as for a single-command tool. Call main(["add", "milk"]) and check the output and return value. For usage errors, expect SystemExit with code 2.
Exercise
A user runs python todo.py add milk -v and gets "unrecognized arguments: -v", although -v is a valid option of the tool. Why does this happen, and what are two ways to make the command work?
Show answer
-v is declared on the top-level parser, so it is only recognized before the command word. The add subparser does not know it and leaves it unparsed, and the top-level parser then reports it as unrecognized. One fix is to run python todo.py -v add milk. The other is to declare -v on the add subparser as well, with its own add_argument call or through a shared parent parser. If you do that, use a different dest from the top-level option so the two values do not collide.
Exercise
You write sub = parser.add_subparsers(dest="command") and run the tool with no arguments. Your handler call args.func(args) crashes with AttributeError. What single change to add_subparsers turns this into a normal usage error with exit status 2?
Show answer
Add required=True, as in parser.add_subparsers(dest="command", required=True). argparse then prints a usage message saying the command argument is required and exits with status 2, before any handler code runs.