Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

including more than one list of arguments with docopt

I'm using for my python application as a command line tool, the feature docopt library. It's easy to implement the commands with that library. But, for now 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 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 to have the following:

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

How do I proceed?

like image 505
Jonathan Prieto-Cubides Avatar asked Mar 28 '15 05:03

Jonathan Prieto-Cubides


Video Answer


1 Answers

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 .

command line :

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

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)

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.

like image 55
Nanook Avatar answered Sep 20 '22 17:09

Nanook