argparse:不显示-h的用法 [英] argparse: don't show usage on -h

查看:77
本文介绍了argparse:不显示-h的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码

from argparse import ArgumentParser
p = ArgumentParser(description = 'foo')
p.add_argument('-b', '--bar', help = 'a description')
p.parse_args()

...结果显示:

$ python argparsetest.py -h
usage: argparsetest.py [-h] [-b BAR]

foo

optional arguments:
  -h, --help         show this help message and exit
  -b BAR, --bar BAR  a description

我想要的是:

$ python argparsetest.py -h
foo

optional arguments:
  -h, --help         show this help message and exit
  -b BAR, --bar BAR  a description

例如,在寻求帮助时没有使用信息.有什么方法可以做到这一点?

e.g., no usage message when asking for help. Is there some way to do this?

推荐答案

绝对有可能-但我不确定记录在案...

definitely possible -- but I'm not sure about documented ...

from argparse import ArgumentParser,SUPPRESS
p = ArgumentParser(description = 'foo',usage=SUPPRESS)
p.add_argument('-b', '--bar', help = 'a description')
p.parse_args()


通过阅读源代码,我一起破解了一些东西,这些东西似乎在显示错误消息时也可以使用... 警告-这些东西主要是 未记录,因此可能随时更改:-)


From reading the source, I've hacked a little something together which seems to work when displaying error messages as well ... warning -- This stuff is mostly undocumented, and therefore liable to change at any time :-)

from argparse import ArgumentParser,SUPPRESS
import sys as _sys
from gettext import gettext as _

class MyParser(ArgumentParser):
    def error(self, message):    
        usage = self.usage
        self.usage = None
        self.print_usage(_sys.stderr)
        self.exit(2, _('%s: error: %s\n') % (self.prog, message))
        self.usage = usage


p = MyParser(description = 'foo',usage=SUPPRESS)
p.add_argument('-b', '--bar', help = 'a description')
p.parse_args()

这篇关于argparse:不显示-h的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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