Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse argument generated help, 'metavar' with choices

When using an argument (optional and positional both have this problem) with the keyword choices, the generated help output shows those choices.

If that same argument also includes a metavar keyword, the list of choices is omitted from the generated output.

What I had in mind, was to show the metavar in the usage line, but actually show the available choices when the 'autohelp' lists positional/optional argument details.

Any simple fixes/workarounds?


I have already started an argparse wrapper for custom help functionality. Perhaps this should be another feature on my TODO list.

like image 302
user2097818 Avatar asked Dec 02 '13 12:12

user2097818


People also ask

What is Metavar in Argparse?

Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument() .

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does argument parser do?

The argparse module makes it easy to write user-friendly command-line interfaces. It parses the defined arguments from the sys. argv . The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments.

What does Nargs do in Argparse?

The add_argument() method action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections.


1 Answers

You can add the choices to the help text.

parser=argparse.ArgumentParser()
parser.add_argument('-f',metavar="TEST",choices=('a','b','c'),
    help='choices, {%(choices)s}')
print parser.format_help()

produces:

usage: stack20328931.py [-h] [-f TEST]

optional arguments:
  -h, --help  show this help message and exit
  -f TEST     choices, {a, b, c}
like image 102
hpaulj Avatar answered Sep 17 '22 16:09

hpaulj