Argparse incorrect order of positional and optional parameters

Why doesn't the argparse argument 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 you pass the panel argument first, it works:

 bar --foo 1 2 3 

Now this in itself is not so bad. I can live with the presence of positional arguments in the first place, that this behavior is incompatible with the argparse help created for us, which claims that the bar should be the last:

usage: argparsetest.py [-h] [--foo FOO [FOO ...]] bar

So how do you do this work with consistent help text?

Here is the complete test program .

+6
source share
2 answers

Perhaps try to do --input - display flags and set these parameters to the required value = True in add_argument?

http://docs.python.org/dev/library/argparse.html#the-add-argument-method

+3
source

nargs='+' tells argparse to collect all other arguments together, so bar included. It has no magical way of guessing that you intend bar be a meaningful argument on its own, and not part of the arguments accepted in --foo .

The example in the docs refers to the simple argument --foo , not nargs='+' . Remember to understand the difference.

+4
source

Source: https://habr.com/ru/post/887109/


All Articles