docopt-ng
docopt-ng is a Jazzband-maintained fork of the original docopt library, providing a humane command-line arguments parser for Python 3.7+. It generates command-line interfaces by parsing a script's docstring, which defines usage patterns and option descriptions. The library aims to offer maintenance, type hints, and complete test coverage. While actively maintained, its release cadence can be irregular, with the latest major release (0.9.0) occurring almost a year ago as of verification.
Warnings
- breaking The 0.9.0 release introduced breaking changes by removing some 'magic' or implicit behaviors to align more strictly with the original `docopt`'s core parsing scope. Users who relied on non-standard docstring patterns or extensions that were previously handled more permissively might experience unexpected parsing or errors. A fix in this release restored compatibility with `docopt` 0.6.2 docstrings, indicating prior parsing discrepancies.
- gotcha If both the original `docopt` library and `docopt-ng` are installed in the same Python environment, the original `docopt` package might take precedence during import due to Python's import resolution order. This can lead to unexpected behavior if `docopt-ng`'s specific features or bug fixes are expected.
- gotcha `docopt-ng` strictly interprets the docstring format. Ambiguities, such as writing `--input ARG` when `--input=ARG` is intended (or vice-versa), or using `-fFILE` which could be interpreted as stacked short options (`-f -i -l`) rather than an option with an argument, can lead to incorrect parsing. Additionally, ensure two spaces separate options from their informal descriptions in the docstring.
- deprecated Prior to version 0.8.0, the `DocoptExit` exception might not have been reliably accessible directly from the `docopt` module's top level. It was explicitly added to `__all__` in version 0.8.0 for easier and more consistent access.
Install
-
pip install docopt-ng
Imports
- docopt
from docopt import docopt
Quickstart
import os
from docopt import docopt
DOC = """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.
"""
# Simulate command line arguments for demonstration
# Replace with sys.argv[1:] in a real application
argv_simulate = os.environ.get('DOCOPT_NG_ARGV_SIMULATE', 'ship Guardian move 100 150 --speed=15').split(' ')
if __name__ == '__main__':
arguments = docopt(DOC, argv=argv_simulate, version='Naval Fate 2.0')
print(arguments)