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

Last updated