Many options with docopt

I would like to use docopt to parse the command line, which can get the same several times. Can someone explain to me how to do this?

Test example:

 #!/usr/bin/env python """ Test program. Usage: test.py -v Options: -v Flag that should be counted """ import docopt print docopt.docopt(__doc__) 

If I run this with test.py -v , I get:

 {'-v': True} 

Where, as if I were running this with test.py -vv , it displays a usage message (indicating that the command line is not valid).

I want to configure option documentation so docopt returns me:

 {'-v': 1} 

When only 1 -v and:

 {'-v': 3} 

If, say, the user passes -vvv . This is almost the same functionality as the count action in argparse .

+4
source share
2 answers

After digging a list of questions related to docopt (closed), I found that the correct way to present this is :

 #!/usr/bin/env python """ Test program. Usage: test.py (-v ...) Options: -v Flag that should be counted """ import docopt print docopt.docopt(__doc__) 

That is, you need to use the symbol " ... " to indicate that the option may appear several times. In this case, the option will be correctly calculated. If the above program is called using test.py -vvv , it will print correctly:

{'-v': 3}

The " ... " symbol can also be used with arguments and parameters that take arguments almost the same, just click the link above for an example.

+7
source

(This is just a comment on the above, but would be awkward as a comment.)

And this can be expanded to pass a list as an argument:

 """ Usage: program (--opt=OPT ...) Options: --opt=OPT An option that can be specified multiple times to form a list """ import docopt print docopt.docopt(__doc__) 

And we run it like

 python test.py --opt=first_option {'--opt': ['first_option']} python test.py --opt=first_option --opt="second in line" {'--opt': ['first_option', 'second in line']} 

And so on.

+2
source

Source: https://habr.com/ru/post/1499163/


All Articles