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
.
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']}