Number of arguments
If you look at the documentation (you still have it open, do you not? 😀), ArgumentParser.add_argument()
also provides the nargs
keyword argument.
This allows you to specify how many values each argument is expecting. Note that argparse
will return a list
for an argument when you specify nargs
.
Here are the available options:
nargs=N
: returns a list ofN
argumentsnargs="?"
: returns zero or one argument (i.e. optional)nargs="*"
: returns a list of zero or more argumentsnargs="+"
: returns a list of one or more argumentsnargs=argparse.REMAINDER
: returns a list from the remainding arguments
Try playing around with these, and examine the output yourself! Try adding multiple arguments or mixing positional and optional arguments too, to see how argparse
behaves with multiple arguments (it is actually pretty smart!)
parser.add_argument("a", nargs=3)
parser.add_argument("b", nargs="?")
parser.add_argument("c", nargs="*")
parser.add_argument("d", nargs="+")
parser.add_argument("e", nargs=argparse.REMAINDER)