Why won't argparse parse these arguments?
--foo 1 2 3 bar
Using
parser = argparse.ArgumentParser()
parser.add_argument('--foo', nargs='+')
parser.add_argument('bar')
which gives the following error:
error: too few arguments
If I pass the bar argument first though, it works:
bar --foo 1 2 3
Now, this in itself is not too bad. I can live with having the positional arguments first it's just that this behaviour is inconsistent with the help argparse creates for us, which states that bar should be last:
usage: argparsetest.py [-h] [--foo FOO [FOO ...]] bar
So how do you make this work with consistent help text?
Here's a complete test program.
There are two types of arguments a Python function can accept: positional and optional.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
A positional argument in Python is an argument whose position matters in a function call. You have likely used positional arguments without noticing. For instance: def info(name, age): print(f"Hi, my name is {name}.
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 .
nargs='+'
tells argparse to gather all remaining args together, so bar
is included. It has no magical way to guess you intend bar
to be a meaningful argument by itself and not part of the args taken to --foo
.
The example in the docs refers to a simple --foo
argument, not one with nargs='+'
. Be sure to understand the difference.
Maybe try doing --input --output flags and setting those options to required=True in the add_argument?
http://docs.python.org/dev/library/argparse.html#the-add-argument-method
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