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.
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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.
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With