Home

Awesome

docopt-ng creates magic command-line interfaces

Test codecov image Jazzband Code style: black

docopt-ng is a fork of the original docopt, now maintained by the jazzband project. Now with maintenance, typehints, and complete test coverage!

docopt-ng helps you create beautiful command-line interfaces magically:

"""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__":
    argv = ["ship", "Guardian", "move", "100", "150", "--speed=15"]
    arguments = docopt(__doc__, argv)
    print(arguments)

results in:

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

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:

python -m pip install docopt-ng

docopt-ng is tested with Python 3.7+.

API

def docopt(
    docstring: str | None = None,
    argv: list[str] | str | None = None,
    default_help: bool = True,
    version: Any = None,
    options_first: bool = False,
    more_magic: bool = False,
) -> ParsedOptions:

docopt takes 6 optional arguments:

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. Furthermore, dot notation is supported, with preceeding dashes (-) and surrounding brackets (<>) ignored, for example arguments.drifting or arguments.x.

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 with usage: (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 occurrences 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 <file> <file> --path=<path>...

I.e. invoked with my_program.py file1 file2 --path=./here --path=./there the returned dict will contain args["<file>"] == ["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:

Examples

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

Development

We would love to hear what you think about docopt-ng on our issues page. Make pull requests, report bugs, and suggest ideas.

To setup your dev environment, fork this repo and clone it locally. We use pdm to manage the project, so install that first.

Then install dev requirements and the package itself as editable, then install the pre-commit hooks:

pdm sync -d -G dev
pdm run pre-commit install

Useful testing, linting, and formatting commands:

pdm run pytest
pdm run black .
pdm run ruff .