Skip to content Skip to sidebar Skip to footer

Is It Possible To Inherit Required Options In Argparse Subparsers?

I am trying to write a command line application that has several modes in which it can run (similar to git having clone, pull, etc.). Each of my subcommands have their own options,

Solution 1:

Separate the main parser and parent parser functionality:

import argparse

parent_parser = argparse.ArgumentParser(description="The parent parser", add_help=False)

parent_parser.add_argument("-p", type=int, required=True,
                           help="set the parent required parameter")


main_parser = argparse.ArgumentParser()
subparsers = main_parser.add_subparsers(title="actions", required=True, dest='command')
parser_command1 = subparsers.add_parser("command1", parents=[parent_parser],
                                      description="The command1 parser",
                                      help="Do command1")
parser_command1.add_argument("--option1", help="Run with option1")

parser_command2 = subparsers.add_parser("command2", parents=[parent_parser],
                                      description="The command2 parser",
                                      help="Do command2")

args = main_parser.parse_args()

The main parser and subparser both write to the same args namespace. If both define a 'p' argument, the subparser's value (or default) will overwrite any value set by the main. So it's possible to use the same 'dest' in both, but it is generally not a good idea. And each parser has to meet its own 'required' specifications. There's no 'sharing'.

The parents mechanism copies arguments from the parent to the child. So it saves typing or copy-n-paste, but little else. It's most useful when the parent is defined elsewhere and imported. Actually it copies by reference, which sometimes raises problems. In general it isn't a good idea to run both the parent and child. Use a 'dummy' parent.


Post a Comment for "Is It Possible To Inherit Required Options In Argparse Subparsers?"