docopt (original) (raw)

docopt creates beautiful command-line interfaces

Video introduction to docopt: PyCon UK 2012: Create *beautiful* command-line interfaces with Python

New in version 0.6.1:

New in version 0.6.0:

Breaking changes:

Isn’t it awesome how optparse and argparse generate help messages based on your code?!

Hell no! You know what’s awesome? It’s when the option parser is_generated based on the beautiful help message that you write yourself! This way you don’t need to write this stupid repeatable parser-code, and instead can write only the help message–_the way you want it.

docopt helps you create most beautiful command-line interfaces_easily_:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)

Beat that! The option parser is generated based on the docstring above that is passed to docopt function. docopt parses the usage pattern ("Usage: ...") and option descriptions (lines starting with dash “-”) and ensures that the program invocation matches the usage pattern; it parses options, arguments and commands based on that. The basic idea is that a good help message has all necessary information in it to make a parser.

Also, PEP 257 recommends putting help message in the module docstrings.

Installation

Use pip or easy_install:

pip install docopt==0.6.2

Alternatively, you can just drop docopt.py file into your project–it is self-contained.

docopt is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy.

API

from docopt import docopt
docopt(doc, argv=None, help=True, version=None, options_first=False)

docopt takes 1 required and 4 optional arguments:

"""Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...]

-h --help    show this
-s --sorted  sorted output
-o FILE      specify output file [default: ./test.txt]
--quiet      print less text
--verbose    print more text

"""

The return value is a simple dictionary with options, arguments and commands as keys, spelled exactly like in your help message. Long versions of options are given priority. For example, if you invoke the top example as:

naval_fate.py ship Guardian move 100 150 --speed=15

the return dictionary will be:

{'--drifting': False,    'mine': False,
 '--help': False,        'move': True,
 '--moored': False,      'new': False,
 '--speed': '15',        'remove': False,
 '--version': False,     'set': False,
 '<name>': ['Guardian'], 'ship': True,
 '<x>': '100',           'shoot': False,
 '<y>': '150'}

Help message format

Help message consists of 2 parts:

Their format is described below; other text is ignored.

Usage pattern format

Usage pattern is a substring of doc that starts withusage: (case insensitive) and ends with a visibly empty line. Minimum example:

"""Usage: my_program.py

"""

The first word after usage: is interpreted as your program’s name. You can specify your program’s name several times to signify several exclusive patterns:

"""Usage: my_program.py FILE
          my_program.py COUNT FILE

"""

Each pattern can consist of the following elements:

Use the following constructs to specify patterns:

If your pattern allows to match argument-less option (a flag) several times:

Usage: my_program.py [-v | -vv | -vvv]

then number of occurences of the option will be counted. I.e.args['-v'] will be 2 if program was invoked as my_program -vv. Same works for commands.

If your usage patterns allows to match same-named option with argument or positional argument several times, the matched arguments will be collected into a list:

Usage: my_program.py --path=...

I.e. invoked with my_program.py file1 file2 --path=./here --path=./there the returned dict will contain args[''] == ['file1', 'file2'] and args['--path'] == ['./here', './there'].

Option descriptions format

Option descriptions consist of a list of options that you put below your usage patterns.

It is necessary to list option descriptions in order to specify:

The rules are as follows:

-q Quit. # GOOD
-o FILE Output file. # GOOD
--stdout Use stdout. # GOOD, 2 spaces

will be ['./here', './there']

--repeatable= [default: ./here ./there]

will be ['./here']

--another-repeatable= [default: ./here]

will be './here ./there', because it is not repeatable

--not-repeatable= [default: ./here ./there]

Examples

We have an extensive list of examples which cover every aspect of functionality of docopt. Try them out, read the source if in doubt.

Subparsers, multi-level help and huge applications (like git)

If you want to split your usage-pattern into several, implement multi-level help (whith separate help-screen for each subcommand), want to interface with existing scripts that don’t use docopt, or you’re building the next “git”, you will need the new options_firstparameter (described in API section above). To get you started quickly we implemented a subset of git command-line interface as an example:examples/git

Data validation

docopt does one thing and does it well: it implements your command-line interface. However it does not validate the input data. On the other hand there are libraries like python schema which make validating data a breeze. Take a look at validation_example.pywhich uses schema to validate data and report an error to the user.

Development

We would love to hear what you think about docopt on our issues page

Make pull requrests, report bugs, suggest ideas and discussdocopt. You can also drop a line directly to <vladimir@keleshev.com>.

Porting docopt to other languages

We think docopt is so good, we want to share it beyond the Python community!

The follosing ports are available:

But you can always create a port for your favorite language! You are encouraged to use the Python version as a reference implementation. A Language-agnostic test suite is bundled with Python implementation.

Porting discussion is on issues page.

Changelog

docopt follows semantic versioning. The first release with stable API will be 1.0.0 (soon). Until then, you are encouraged to specify explicitly the version in your dependency tools, e.g.:

pip install docopt==0.6.2