问题
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