wujek
wujek

Reputation: 11040

Python argparse - disable help for subcommands?

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?

Upvotes: 5

Views: 8356

Answers (3)

Samuel
Samuel

Reputation: 8905

Short answer, add "add_help=False" to ArgumentParser, like this:

parser = argparse.ArgumentParser(add_help=False)

This is from https://docs.python.org/2/library/argparse.html#add-help.

Upvotes: 1

poli_g
poli_g

Reputation: 639

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

Upvotes: 2

hpaulj
hpaulj

Reputation: 231365

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

Upvotes: 3

Related Questions