Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse: default for positional argument not working?

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?

like image 915
GhostCat Avatar asked Apr 13 '17 11:04

GhostCat


People also ask

What are positional arguments in 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.

How do you make Argparse arguments mandatory?

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 .

What command-line argument does the ArgumentParser provide by default?

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 .

What is action Store_true in Argparse?

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.


1 Answers

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.

like image 74
Squizz Avatar answered Oct 19 '22 23:10

Squizz