pythoncommand-linecommand-line-interfacedocopt

How do I make an argument with unknown n number of values stored in an array when parsed using docopt


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?


Solution

  • 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)