jazzband / docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
MIT License
177 stars 20 forks source link
argparse argument-parser docopt docopt-ng mypy optparse python3

docopt-ng creates beautiful command-line interfaces

Test codecov image Jazzband Ruff

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:

"""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,
    argv: list[str] | str | None = None,
    default_help: bool = True,
    version: Any = None,
    options_first: bool = False,
) -> ParsedOptions:

docopt takes a docstring, and 4 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 create a virtual env, install dev requirements and the package itself as editable, then install the pre-commit hooks:

pdm sync --dev --group dev
pdm run pre-commit install

Useful testing, linting, and formatting commands:

pdm run pytest
pdm run ruff check .
pdm run ruff format .