Python argparse - 禁用子命令的帮助? [英] Python argparse - disable help for subcommands?

查看:31
本文介绍了Python argparse - 禁用子命令的帮助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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?

推荐答案

子解析器创建于:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆