Back to results for “Scope”
Python › Command-Line Interfaces (argparse)

How do you implement subcommands (like 'git commit' or 'git push') using argparse's add_subparsers()?

Advanced

Answer

Call add_subparsers() on the main parser to create a subparser group, then add each subcommand as its own separate ArgumentParser (via add_parser()) with its own specific arguments — each subcommand's parsed arguments merge into the same top-level Namespace, distinguished by a 'dest' attribute indicating which subcommand was invoked.
parser = argparse.ArgumentParser(prog="mytool")
subparsers = parser.add_subparsers(dest="command", required=True)

push_parser = subparsers.add_parser("push")
push_parser.add_argument("remote")

commit_parser = subparsers.add_parser("commit")
commit_parser.add_argument("-m", "--message", required=True)

args = parser.parse_args(["commit", "-m", "Initial commit"])
print(args.command, args.message)  # commit Initial commit
Real-world example Building a multi-command CLI tool like a custom deployment or database migration utility with distinct subcommands, each with its own arguments.

Common follow-ups: How would you dispatch to a different handler FUNCTION based on which subcommand (args.command) was actually invoked?