Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse incorrect order of positional and optional parameters

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.

like image 279
Reimund Avatar asked May 02 '11 08:05

Reimund


People also ask

Can positional arguments be optional?

There are two types of arguments a Python function can accept: positional and optional.

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What are positional arguments in Python?

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}.

How do you make an argument compulsory in Python?

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 .


2 Answers

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.

like image 149
Eli Bendersky Avatar answered Nov 15 '22 12:11

Eli Bendersky


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

like image 38
Sweet Sheep Avatar answered Nov 15 '22 12:11

Sweet Sheep