Python argparse - 禁用子命令的帮助?
Python argparse - disable help for subcommands?
我在 Python 3.5.1 上使用 argparse。我不想要默认的帮助命令,所以我使用 ArgumentParser 构造函数的 add_help=False 参数禁用了它。然而,虽然删除了应用程序的帮助命令,但它们仍然存在于子命令中。
如何删除 subcommands/subparsers 的帮助?
子解析器创建于:
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
,子解析器可以获得大部分(如果不是全部)主解析器可以获得的参数。
我得测试一下。
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
禁用我内置到 argparse 中的 -h / --help 标志的选项。
看看这个:
简答,将“add_help=False”添加到 ArgumentParser,如下所示:
parser = argparse.ArgumentParser(add_help=False)
这是来自https://docs.python.org/2/library/argparse.html#add-help.
我在 Python 3.5.1 上使用 argparse。我不想要默认的帮助命令,所以我使用 ArgumentParser 构造函数的 add_help=False 参数禁用了它。然而,虽然删除了应用程序的帮助命令,但它们仍然存在于子命令中。 如何删除 subcommands/subparsers 的帮助?
子解析器创建于:
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
,子解析器可以获得大部分(如果不是全部)主解析器可以获得的参数。
我得测试一下。
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
禁用我内置到 argparse 中的 -h / --help 标志的选项。
看看这个:
简答,将“add_help=False”添加到 ArgumentParser,如下所示:
parser = argparse.ArgumentParser(add_help=False)
这是来自https://docs.python.org/2/library/argparse.html#add-help.