Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top