Reputation: 4821
I would like to parse an optional argument with multiple values with docopt
. Below is the example usage.
my_program.py --loc pcg acc
# or anything that achieve similar result
and after parsing, I expect that to have a python list like so
arguments["--loc"] = ["pcg", "acc"]
I browsed around and found out if this is doable in argparse
by passing nargs
argument.
I couldn't find any similar way in docopt
, is this doable in docopt
? If not, what's the alternative?
An alternative that I can think of is to ask user specify value separated by comma and manually split it during parsing as below.
my_program.py [--loc=<comma_separated_str>]
In the python
code
locs = arguments["--loc"].split(",") if arguments["--loc"] else []
However, that seems ugly, so I'm looking for a proper way to do so with docopt
.
Upvotes: 0
Views: 1137
Reputation: 379
The definition you are looking for is probably
"""
Usage: my_program.py --help
my_program.py [(--loc <loc>) [<loc>...]]
"""
from docopt import docopt
print(docopt(__doc__))
Multiple --loc
values are provided with spaces between them
python3 my_program.py --loc pcg acc hah
{'--help': False,
'--loc': True,
'<loc>': ['pcg', 'acc', 'hah']}
The --loc
argument is indeed optional
$ python3 my_program.py
{'--help': False,
'--loc': False,
'<loc>': []}
Providing no values for --loc
results in an error
$ python3 my_program.py --loc
Usage: my_program.py --help
my_program.py [(--loc <loc>) [<loc>...]]
If --loc
could be used without any value, this simpler definition will do
"""
Usage: my_program.py --help
my_program.py [--loc <loc> ...]
"""
from docopt import docopt
print(docopt(__doc__))
resulting in
$ python3 my_program.py --loc
{'--help': False,
'--loc': True,
'<loc>': []}
It is otherwise equivalent to the first definition
Upvotes: 0
Reputation: 5031
One approach would be to use the elipsis (...) operator, so that an option can be repeated zero or more times with square brackets, or one or more times with parenthesis . For example
"""Usage: my_program.py --help
my_program.py [--loc=<loc>]...
"""
from docopt import docopt
print(docopt(__doc__))
would give the following output
$ python my_program.py --loc=pcg --loc=acc
{'--help': False,
'--loc': ['pcg', 'acc']}
Upvotes: 2