Python argparse-禁用子命令帮助吗? [英] Python argparse - disable help for subcommands?
问题描述
我在python 3.5.1上使用argparse.我不需要默认的帮助命令,因此我使用ArgumentParser构造函数的add_help = False参数将其禁用.但是,尽管删除了应用程序的帮助命令,但对于子命令它们仍然存在. 如何删除子命令/子解析器的帮助?
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?
推荐答案
子解析器在以下位置创建:
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)
...
执行add_parser
时似乎可以传递add_help=False
参数.借助**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.
我必须对其进行测试.
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
这篇关于Python argparse-禁用子命令帮助吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!