argparse

Nested subparsers

Nested subparsers can become in handy when one wants to have one or more level of commands, and also, only allow specific arguments to a certain command or subcommand.

The example below should illustrate this:

nested_subparsers.py
def main():

    parser = argparse.ArgumentParser()
    
    subparsers = parser.add_subparsers(help="commands")
    cmd1 = subparsers.add_parser("cmd1")
    cmd2 = subparsers.add_parser("cmd2")
    
    subcmd = cmd1.add_subparsers(help="subcommands")
    subcmd_cmd1_parser = subcmd.add_parser("subcmd1")
    subcmd_cmd1_parser.add_argument("--argument", "-a")

    args = parser.parse_args()
    print(args)

In this case, we have two commands, cmd1 and cmd2. For cmd1 there exists a subcommand subcmd1, which can use the -a argument. On the other hand, cmd2 have no further subcommands or arguments available.

Example output

$ python nested_subparsers.py --help
usage: nested_subparsers.py [-h] {cmd1,cmd2} ...

positional arguments:
  {cmd1,cmd2}  commands

options:
  -h, --help   show this help message and exit
$ python nested_subparsers.py cmd1 --help
usage: nested_subparsers.py cmd1 [-h] {subcmd1} ...

positional arguments:
  {subcmd1}   subcommands

options:
  -h, --help  show this help message and exit
$ python nested_subparsers.py cmd1 subcmd1 --help
usage: nested_subparsers.py cmd1 subcmd1 [-h] [--argument ARGUMENT]

options:
  -h, --help            show this help message and exit
  --argument ARGUMENT, -a ARGUMENT
$ python nested_subparsers.py cmd2 --help
usage: nested_subparsers.py cmd2 [-h]

options:
  -h, --help  show this help message and exit

Last updated