I\'ve looked through dozens of similar SO questions but haven\'t find suitable solutions so please forgive me in case of a dublicate. I have a problem similar to this one
<
For a start let's distinguish between parsing behavior and help display.
I assume you have multiple subparsers (otherwise why use the subparser mechanism). -o
is an argument specific to sub_option
, and presumably the other subparsers have their own arguments.
What is the purpose of -c
? Is it something that is common to all subparsers? Since subparsers are required, it doesn't make sense to talk about an argument that only matters to the main parser.
One way to deal with a common argument is to define it for all subparsers. The parents mechanism that you use saves you a bit of typing. Just omit it from the main parser
definition. That gets rid of the problem with having to supply it twice.
If -c
is defined for all the subparsers, then there isn't a need to show it in the main parser help, is there?
The whole subparser mechanism is cleanest when the subparser command is the 1st argument string, with all of its arguments, positionals and options following. It's possible to define arguments for the main parser, but it often complicates both use and help.
The issue of display the help for both the main parser and (all) the subparsers has come up before, both on SO, and on the python bug/issues. There isn't a simple solution. Some tools that may help are:
generate help under program control with parser.print_help()
, and subparse.print_help()
.
add_subparsers() command takes parameters like prog
, title
and description
which can be used to control the help, including the usage
of the subparser help.
add_subparser() takes the same sort of parameters as ArgumentParser
(since it defines a parser), description
and usage
may be useful.
Looking a previous question
How to show help for all subparsers in argparse?
I realized that if -c
is not required, it can be defined for both the main and subparser, and appear as expected in the helps. But by making it 'required', both parsers have to see it - but only the value seen by the subparser appears in the namespace.
Also positionals defined in the main parser appear in the subparser usage.
Another subparsers help display question
argparse subparser monolithic help output
http://bugs.python.org/issue20333 argparse subparser usage message hides main parser usage
discusses the question of how much of main parser usage should show up in the subparse usage line. Currently just positionals (defined before the subparsers) show up. In the patch I suggest adding required optionals as well. But you can always fudge this by defining your own prog
for subparsers.