2

I want a command line argument to be in an array format.

i.e

myprogram.py -a 1,2,4,5

and when the argument is parsed using docopt, I want to see:

{'a' = [1,2,4,5]}  # the length of this array could be as long as user may like.

I don't know if this is possible or not. If not what is the best adjustment I could make?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Dhruv Patel
  • 426
  • 3
  • 9
  • 19

2 Answers2

3

You will not get docopt to do this, as the comma separated list is just considered a optional argument. But you could easily do it yourself afterwards:

"""
Example of program with many options using docopt.

Usage:
  myprogram.py -a NUMBERS

Options:
  -h --help            show this help message and exit
  -a NUMBERS           Comma separated list of numbers
"""

from docopt import docopt

if __name__ == '__main__':
    args = docopt(__doc__, version='1.0.0rc2')
    args['-a'] = [int(x) for x in args['-a'].split(',')]
    print(args)
vvvvv
  • 25,404
  • 19
  • 49
  • 81
J. P. Petersen
  • 4,871
  • 4
  • 33
  • 33
2

The correct answer would be to use an ellipsis ...

From the docopt documentation

... (ellipsis) one or more elements. To specify that arbitrary number of repeating elements could be accepted, use ellipsis (...), e.g. my_program.py FILE ... means one or more FILE-s are accepted. If you want to accept zero or more elements, use brackets, e.g.: my_program.py [FILE ...]. Ellipsis works as a unary operator on the expression to the left.

Using the online parser you can see the output.

Given a docopt of

Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py -h | --help
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.

An input of ship new 1 2 3 4 will give you the following parsed information

{
  "--help": false, 
  "--version": false, 
  "<name>": [
    "1", 
    "2", 
    "3", 
    "4"
  ], 
  "new": true, 
  "ship": true
}
Steve
  • 25,806
  • 2
  • 33
  • 43
  • Nice to know that this option exists too. However, I've not been able to get this to work with `--name` so that the command would be something like `naval_fate.py ship new --name=1 2 3 4` instead. – Ryan H. May 28 '20 at 00:29