Using docopt double dash option with optional parameter?

497 Views Asked by At

Using docopt, is there a way to make a double-dashed parameter that works with and without an equals sign?

I want both of the following commands to make --tls be true:

cmd --tls
cmd --tls=true

I seem to only be able to get one or the other to work by using

Options:
  --tls

or

Options:
  --tls=false                  

Separating them by a comma does not seem to work

Options:
  --tls, --tls=false                  
1

There are 1 best solutions below

0
On

I have the same problem. I can't find a solution, but here's the best work-around I've got:

"""
Usage:
  test.py [tls [--true|--false]]
"""
from docopt import docopt
arguments = docopt(__doc__)
if arguments['tls'] and not (arguments['--true'] or arguments['--false']):
    arguments['--true'] = True

so argument options would be:

cmd
cmd tls
cmd tls --true
cmd tls --false

note that this is case sensitive, there may be bugs if you capitalize TLS: https://github.com/docopt/docopt/issues/460

 

another option:

"""
Usage:
    script.py [--tls [<tlsval>]]
"""
from docopt import docopt
arguments = docopt(__doc__)
assert arguments['<tlsval>'] in (None, 'true', 'false'), "invalid tls value -- expected true or false"

 

 

sorry for all the edits, but here's one more:

"""
Usage:
   script.py [--MAS|--GPI [RESEND|ADD|REMOVE|SKU]]

Options:
    --MAS                   only do MAS step
    --GPI                   only do GPI step, optionally specify ADD/REMOVE/SKU (default is RESEND)
        RESEND            only GPI, strategy=RESEND (default for --GPI)
        ADD               only GPI, strategy=ADD
        REMOVE            only GPI, strategy=REMOVE
        SKU               only GPI, strategy=SKU
"""
from docopt import docopt
arguments = docopt(__doc__)
strategy = [k for k in ['RESEND', 'ADD', 'REMOVE', 'SKU'] if arguments[k]]
strategy = strategy[0] if strategy else "RESEND" #resend is default

This one gets you the --argument but can't have the = after the --argument