Reputation: 5299
I would like to using docopt
for parsing a command line that can receive the same option multiple times. Could somebody explain me how to do it?
A test example:
#!/usr/bin/env python
"""
Test program.
Usage:
test.py -v
Options:
-v Flag that should be counted
"""
import docopt
print docopt.docopt(__doc__)
If I run this with test.py -v
, I get:
{'-v': True}
Where as if I run this with test.py -vv
, it displays the usage message (indicating the command line is not valid).
I'd like to tweak the option documentation so that docopt
returns me:
{'-v': 1}
When only 1 -v
was passed and:
{'-v': 3}
If, say, the user passed -vvv
. This is pretty much the same functionality the count
action in argparse.
Upvotes: 4
Views: 2900
Reputation: 1072
(This is just a comment to the above, but would get awkward as a comment.)
And this can be extended to passing a list as an argument:
"""
Usage:
program (--opt=OPT ...)
Options:
--opt=OPT An option that can be specified multiple times to form a list
"""
import docopt
print docopt.docopt(__doc__)
And we run this as
python test.py --opt=first_option
{'--opt': ['first_option']}
python test.py --opt=first_option --opt="second in line"
{'--opt': ['first_option', 'second in line']}
And so on.
Upvotes: 2
Reputation: 5299
After digging the docopt (closed) issue list, I have found that the right way to represent this would be:
#!/usr/bin/env python
"""
Test program.
Usage:
test.py (-v ...)
Options:
-v Flag that should be counted
"""
import docopt
print docopt.docopt(__doc__)
That is, one must use the symbol "...
" to signify that an option may appear multiple times. In this case, the option will be correctly counted. If the above program is called with test.py -vvv
, it will correctly print:
{'-v': 3}
The symbol "...
" can also be used with arguments and options that take arguments pretty much the same way, just hit the link above for an example of that.
Upvotes: 8