My script defines one main parser and multiple subparsers. I want to apply the -p argument to some subparsers. So far the code looks like this:
parser = argparse.ArgumentParser(prog="myProg")
subparsers = parser.add_subparsers(title="actions")
parser.add_argument("-v", "--verbose",
action="store_true",
dest="VERBOSE",
help="run in verbose mode")
parser_create = subparsers.add_parser ("create",
help = "create the orbix environment")
parser_create.add_argument ("-p",
type = int,
required = True,
help = "set db parameter")
# Update
parser_update = subparsers.add_parser ("update",
help = "update the orbix environment")
parser_update.add_argument ("-p",
type = int,
required = True,
help = "set db parameter")
As you can see the add_arument ("-p") is repeated twice. I actually have a lot more subparsers. Is there a way to loop through the existing subparsers in order to avoid repetition?
For the record, I am using Python 2.7
Update by @hpaulj
Due to changes in handling subparsers since 2011, it is a bad idea to use the main parser as a
parent. More generally, don’t try to define the same argument (samedest) in both main and sub parsers. The subparser values will overwrite anything set by the main (even the subparserdefaultdoes this). Create separate parser(s) to use asparents. And as shown in the documentation, parents should useadd_help=False.Original answer
This can be achieved by defining a parent parser containing the common option(s):
This produces help messages of the format:
Output:
Output:
However, if you run your program, you will not encounter an error if you do not specify an action (i.e.
createorupdate). If you desire this behavior, modify your code as follows.This fix was brought up in this SO question which refers to an issue tracking a pull request.