9

I am using the docopt library.

I couldn't find out the way to accomplish the following requirement:

The docstring is:

"""
aTXT tool

Usage:
  aTXT <source>... [--ext <ext>...]

Options:
    --ext       message

"""

From the shell, I want to write something like this:

atxt a b c --ext e f g

The result dictionary from docopt output is the following:

 {'--ext': True,
 '<ext>': [],
 '<source>': ['a', 'b', 'c', 'e', 'f']}

But, I need it to be the following:

 {'--ext': True,
 '<ext>': ['e', 'f', 'g'],
 '<source>': ['a', 'b', 'c']}

How do I proceed?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Jonathan Prieto-Cubides
  • 2,577
  • 2
  • 18
  • 17

1 Answers1

9

I have not been able to find a way of passing a list directly into the Docopt argument dictionary. However, I have worked out a solution that has allowed me to pass a string into Docopt, then convert that string into a list.

There are issues with your Docopt __doc__ and I revised them so that I could test the solution specific to your case. This code was written in Python 3.4 .

In command line:

python3 gitHubTest.py a,b,c -e 'e,f,g'

In gitHubTest.py:

"""
aTXT tool

Usage:
  aTXT.py [options] (<source>)

Options:
  -e ext, --extension=ext    message

"""
from docopt import docopt

def main(args) :
    if args['--extension'] != None:
        extensions = args['--extension'].rsplit(sep=',')
        print (extensions)

if __name__ == '__main__':
    args = docopt(__doc__, version='1.00')
    print (args)
    main(args)

It returns:

{
'--extension': 'e,f,g',
'<source>': 'a,b,c'
}
['e', 'f', 'g']

The variable extensions created in main() is now the list you were hoping to pass in.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Nanook
  • 153
  • 2
  • 8
  • 1
    I wish there was a way to do it properly with docopt... As far as I understand, having multiple lists like OP wants is totally legitimate. And it's possible with argparse: https://stackoverflow.com/a/32763023/4671300 – talz May 29 '18 at 20:29