0

I use docopt to handle the arguments of my scripts.

I have a case where I would like to allow to "add" or "delete" something in my script. The "add" or "delete" action is not manadatory, but if either is chosen then it requires a parameter (the "thing" to "add" or "delete")

How can I combine:

  • two optional parameters (mutually exclusive) defined via [-a|-d]
  • with a mandatory parameter, should any of -a or -d be provided?

I tried several variations of conditional nesting, such as

"""
Usage:
    hello.py [[-a|-d] FILE]

Options:
    -a  add a file
    -d  delete a file
    FILE file to be added or deleted
"""

import docopt

args = docopt.docopt(__doc__)
print(args)

but the script runs, despite just giving -a as an argument (it should dump the help, as one of the parameters is missing)

WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

0

I found a way, via multiple Usage entries:

"""
Usage:
    hello.py [-a|-d] FILE
    hello.py

Options:
    -a  add a file
    -d  delete a file
    FILE file to be added or deleted
"""

import docopt

args = docopt.docopt(__doc__)
print(args)

This allows for two (or more) cases: when there are no arguments, or when there is either -a or -d + a compulsory FILE

WoJ
  • 27,165
  • 48
  • 180
  • 345