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:
Solution 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 _
classMyParser(ArgumentParser):
deferror(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()
Solution 2:
Note: to not show usage for a specific argument, use
parser.add_argument('--foo', help=argparse.SUPPRESS)
per the documentation.
Solution 3:
One additional note: if you don't want help at all you can construct the parser with add_help=False
def parse_args():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("arg")
return parser.parse_known_args()
def main():
args, remaining = parse_args()
print(args)
print(remaining)
if __name__ == '__main__':
main()
user@host % python3 /tmp/test.py f
Namespace(arg='f')
[]
user@host % python3 /tmp/test.py f -h
Namespace(arg='f')
['-h']
user@host % python3 /tmp/test.py f -h --help
Namespace(arg='f')
['-h', '--help']
user@host %
Post a Comment for "Argparse: Don't Show Usage On -h"