argparse:不要在 -h 上显示用法 [英] argparse: don't show usage on -h
本文介绍了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屋!
查看全文