Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Python Argparse to list choices only once?

I have code that looks like:

list_of_choices = ["foo", "bar", "baz"]
parser = argparse.ArgumentParser(description='some description')
parser.add_argument("-n","--name","-o","--othername",dest=name,
    choices=list_of_choices

and what I get for output looks like:

-n {foo,bar,baz}, --name {foo,bar,baz}, -o {foo,bar,baz}, 
--othername {foo,bar,baz}

What I would like is:

-n, --name, -o, --othername {foo,bar,baz}

For context, there are historical reasons why we need two names for the same option and the actual list of choices is 22 elements long, so it looks much worse than the above.

This problem is subtly different than Python argparse: Lots of choices results in ugly help output in that I am not working with two separate options and it is okay to have it all on the line as above.

like image 315
coyot Avatar asked Nov 20 '12 18:11

coyot


People also ask

How do you add an optional argument in Argparse?

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

What is Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.

What is Metavar?

metavar is the name for the argument in usage messages. dest is the name of the attribute to be added to the object. This object is returned by parse_args .


1 Answers

I think you might want multiple add_arguments() and only set choices on the one where you want the choices.

list_of_choices = ["foo", "bar", "baz"]
parser = argparse.ArgumentParser(description='some description')
parser.add_argument("-n")
parser.add_argument("--name")
parser.add_argument("-o")
parser.add_argument("--othername", dest='name',
    choices=list_of_choices)
like image 130
Thomas Schultz Avatar answered Sep 19 '22 19:09

Thomas Schultz