8

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.

2
  • 1
    Ran into the same issue just now. One can use -- to end nargs globbing, so --foo 1 2 3 -- bar should work in your example above. It really should be solved automatically, reserving the number of arguments needed for positional arguments, in my opinion. There are discussions on this open issue at bugs.python.org/issue9338 and bugs.python.org/issue9182 (at the very least it should be clearly documented). Commented Apr 21, 2013 at 12:24
  • -- to stop the list is so cool. this is my favourite answer. Commented Oct 19, 2020 at 11:15

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It would be easy to implement it so that the last n arguments are treated as the n mandatory positional arguments. It's not magic, I guess it's just a design decision.
3

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

2 Comments

Thanks, that works and gives me consistent help text. The only drawback is the extra --input flag part but I can live with that. Cheers
To clear things up, the suggested solution is to use parser.add_argument('--bar', required=True). One can then pass the following arguments: --foo 1 2 3 --bar bar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.