I have:
from argparse import ArgumentParser
parser = ArgumentParser(description='Test')
parser.add_argument("command",
help="the command to be executed",
choices=["dump", "delete", "update", "set"],
default="set")
parser.parse_args()
But when I run: python test.py
I get:
usage: test.py [-h] {dump,delete,update,set}
test.py: error: too few arguments
Maybe I am just blind sighted today; but I can't figure what should be wrong about my input. Or is this simply not possible with argparse?
Python argparse positional arguments The example expects two positional arguments: name and age. parser.add_argument('name') parser.add_argument('age') Positional arguments are created without the dash prefix characters.
required is a parameter of the ArugmentParser object's function add_argument() . By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .
Parsing arguments In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv .
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.
For default
keyword argument to work, you have to add nargs='*'
like below:
parser.add_argument("command",
help="the command to be executed",
choices=["dump", "delete", "update", "set"],
nargs='?',
default="set"
)
See https://docs.python.org/2/library/argparse.html#default for more information :)
Edit by OP: nargs='*'
allows for multiple commands to be entered. Thus changed to nargs='?'
as I am looking for exactly one command to be entered.
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