10

I'd like to design my command line application in a way that one option, let's call it comment, can be specified several times, e.g.,

$ ./my_app.py --comment="Comment 1" --comment="Comment 2"

Can this be done with docopt? I checked the docopt homepage but couldn't find any reference to multiple occurences of the same optional argument.

andreas-h
  • 10,679
  • 18
  • 60
  • 78
  • 1
    I'm not sure about docopt, but with argparse you can do it using [append action](http://docs.python.org/dev/library/argparse.html#action) – smeso Dec 09 '13 at 10:11

2 Answers2

5

For reference, the official docs can be found here at github.

To answer your specific question, you can use an ellipse ... with your optional option [--my-option] and specify that your option takes an argument.

I.e. [--my-option=ARG]... or [--my-option=<arg>]...

Example:

"""
Usage:
    my_program [--comment=ARG]... FILE

Arguments:
    FILE       An argument for passing in a file.

Options:
    --comment  Zero or more comments
"""

By specifying it as [--comment=<arg>]... you ensure that opt['--comment'] is a list of all the specified comments.

Executing: my_program --comment=ASDF --comment=QWERTY my_file

Leads to:

if __name__ == '__main__':
    opts = docopt(__doc__)
    opts['--comment'] == ['ASDF', 'QWERTY']
    opts['FILE'] == 'my_file'
tgray
  • 8,826
  • 5
  • 36
  • 41
3

You can use ... to indicate a repeating element and [ ] to indicate that it is optional:

my_program [comment]...

This indicates comment is optional and can be repeated.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • But omits the `--comment` part: In my case, I have other required positional arguments, and this would be hard to discern, and potentially ambiguous. (e.g., I'd like `./myprog.py --comment "ASDF" --comment "QWERTY" my_file`) – Thanatos Mar 04 '14 at 23:00