argparse: don't show usage on -h

浪子不回头ぞ 提交于 2020-01-04 03:15:11

问题


The code

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

...results in the output:

$ 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

What I'd like is:

$ 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?


回答1:


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()



回答2:


Note: to not show usage for a specific argument, use

parser.add_argument('--foo', help=argparse.SUPPRESS)

per the documentation.



来源:https://stackoverflow.com/questions/14591168/argparse-dont-show-usage-on-h

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!