'Docopt - Multiple values for an optional argument
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user368683 |
