Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: don't display 'choices' with argparse

With argparse, I have the following line:

parser.add_argument("-p", "--parameter", type=str, default=None, nargs='+',
                        help="some option",
                        choices=allValues.keys()
                        )

The resulting help message shows all values in allValues:

-p {a ,b ,c , d, e, f, g, h, i, l, m; a ,b ,c , d, e, f, g, h, i, l, m} [{a ,b ,c , d, e, f, g, h, i, l, m} ...], --parameter {a ,b ,c , d, e, f, g, h, i, l, m; a ,b ,c , d, e, f, g, h, i, l, m} [{a ,b ,c , d, e, f, g, h, i, l, m; a ,b ,c , d, e, f, g, h, i, l, m} ...] some option

Can I remove {a ,b ,c , d, e, f, g, h, i, l, m; a ,b ,c , d, e, f, g, h, i, l, m} from above and just display the name of the parameter and the help message?

like image 827
Ricky Robinson Avatar asked Jul 18 '13 15:07

Ricky Robinson


People also ask

What is the use of argparse in Python?

Argparse Module The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments. Steps for Using Argparse

What is the default value of--color argument in Python argparse?

The default value would be blue if --color argument is not defined. With python argparse, you must declare your positional arguments explicitly. If you do not, the parser expects to have no arguments left over after it completes parsing, and it raises an error if arguments still remain.

Do you have to declare positional arguments in argparse?

With python argparse, you must declare your positional arguments explicitly. If you do not, the parser expects to have no arguments left over after it completes parsing, and it raises an error if arguments still remain. How do we define optional and positional arguments?

How do I make an option required in argparse?

required¶ In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. To make an option required, True can be specified for the required= keyword argument to add_argument(): >>>


1 Answers

Use the metavar argument::

parser.add_argument("-p", "--parameter", type=str, default=None, nargs='+',
                    help="some option",
                    choices=allValues.keys(),
                    metavar='PARAMETER'
                    )

This will give::

-p PARAMETER, --parameter PARAMETER some option

If you don't want to show a metavariable at all you could consider passing '' to metavar. Otherwise, I believe you will have to create your own custom formatter classes and pass that to the ArgumentParser.

like image 156
SethMMorton Avatar answered Oct 19 '22 19:10

SethMMorton