Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse: don't show usage on -h

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?

like image 883
elhefe Avatar asked Jan 14 '23 08:01

elhefe


1 Answers

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()
like image 110
mgilson Avatar answered Jan 22 '23 06:01

mgilson