问题
I'm using argparse on Python 3.5.1. I don't want the default help commands, so I disabled it using the add_help=False argument to the ArgumentParser constructor. However, while the help commands for the application are removed, they still exist for the subcommands. How can I remove the help for the subcommands/subparsers?
回答1:
The subparser is created in:
class _SubParsersAction(Action):
....
def add_parser(self, name, **kwargs):
...
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
...
It looks like I could pass the add_help=False
parameter when doing add_parser
. With **kwargs
, the subparser can get most, if not all, the parameters that a main one can get.
I'll have to test it.
In [721]: p=argparse.ArgumentParser(add_help=False)
In [722]: sp=p.add_subparsers()
In [723]: p1=sp.add_parser('test',add_help=False)
In [724]: p.print_help() # no -h for main
usage: ipython3 {test} ...
positional arguments:
{test}
In [725]: p1.print_help() # no -h for sub
usage: ipython3 test
In [727]: p.parse_args(['-h'])
usage: ipython3 {test} ...
ipython3: error: unrecognized arguments: -h
...
In [728]: p.parse_args(['test','-h'])
usage: ipython3 {test} ...
ipython3: error: unrecognized arguments: -h
回答2:
The option to disable the -h / --help flag i built in into argparse.
Take a look at this:
https://docs.python.org/2/library/argparse.html#add-help
来源:https://stackoverflow.com/questions/37356411/python-argparse-disable-help-for-subcommands