Python argparse - disable help for subcommands?

拥有回忆 提交于 2019-12-25 07:25:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!