• Stars
    star
    149
  • Rank 240,660 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created about 5 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.

docopt-ng creates beautiful 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:

"""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:

  • docstring is a string that contains a help message that will be used to create the option parser. The simple rules of how to write such a help message are given in next sections. Typically you would just use __doc__.

  • argv is an optional argument vector; by default docopt uses the argument vector passed to your program (sys.argv[1:]). Alternatively you can supply a list of strings like ["--verbose", "-o", "hai.txt"], or a single string that will be split on spaces like "--verbose -o hai.txt".

  • default_help, by default True, specifies whether the parser should automatically print the help message (supplied as doc) and terminate, in case -h or --help option is encountered (options should exist in usage pattern, more on that below). If you want to handle -h or --help options manually (as other options), set help=False.

  • version, by default None, is an optional argument that specifies the version of your program. If supplied, then, (assuming --version option is mentioned in usage pattern) when parser encounters the --version option, it will print the supplied version and terminate. version could be any printable object, but most likely a string, e.g. "2.1.0rc1".

    Note, when docopt is set to automatically handle -h, --help and --version options, you still need to mention them in usage pattern for this to work. Also, for your users to know about them.

  • options_first, by default False. If set to True will disallow mixing options and positional argument. I.e. after first positional argument, all arguments will be interpreted as positional even if the look like options. This can be used for strict compatibility with POSIX, or if you want to dispatch your arguments to other programs.

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:

  • Usage pattern, e.g.:

    Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...]
    
  • Option descriptions, e.g.:

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

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:

  • <arguments>, ARGUMENTS. Arguments are specified as either upper-case words, e.g. my_program.py CONTENT-PATH or words surrounded by angular brackets: my_program.py <content-path>.
  • --options. Options are words started with dash (-), e.g. --output, -o. You can "stack" several of one-letter options, e.g. -oiv which will be the same as -o -i -v. The options can have arguments, e.g. --input=FILE or -i FILE or even -iFILE. However it is important that you specify option descriptions if you want your option to have an argument, a default value, or specify synonymous short/long versions of the option (see next section on option descriptions).
  • commands are words that do not follow the described above conventions of --options or <arguments> or ARGUMENTS, plus two special commands: dash "-" and double dash "--" (see below).

Use the following constructs to specify patterns:

  • [ ] (brackets) optional elements. e.g.: my_program.py [-hvqo FILE]
  • ( ) (parens) required elements. All elements that are not put in [ ] are also required, e.g.: my_program.py --path=<path> <file>... is the same as my_program.py (--path=<path> <file>...). (Note, "required options" might be not a good idea for your users).
  • | (pipe) mutually exclusive elements. Group them using ( ) if one of the mutually exclusive elements is required: my_program.py (--clockwise | --counter-clockwise) TIME. Group them using [ ] if none of the mutually-exclusive elements are required: my_program.py [--left | --right].
  • ... (ellipsis) one or more elements. To specify that arbitrary number of repeating elements could be accepted, use ellipsis (...), e.g. my_program.py FILE ... means one or more FILE-s are accepted. If you want to accept zero or more elements, use brackets, e.g.: my_program.py [FILE ...]. Ellipsis works as a unary operator on the expression to the left.
  • [options] (case sensitive) shortcut for any options. You can use it if you want to specify that the usage pattern could be provided with any options defined below in the option-descriptions and do not want to enumerate them all in usage-pattern.
  • "[--]". Double dash "--" is used by convention to separate positional arguments that can be mistaken for options. In order to support this convention add "[--]" to your usage patterns.
  • "[-]". Single dash "-" is used by convention to signify that stdin is used instead of a file. To support this add "[-]" to your usage patterns. "-" acts as a normal command.

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:

  • synonymous short and long options,
  • if an option has an argument,
  • if option's argument has a default value.

The rules are as follows:

  • Every line in doc that starts with - or -- (not counting spaces) is treated as an option description, e.g.:

    Options:
      --verbose   # GOOD
      -o FILE     # GOOD
    Other: --bad  # BAD, line does not start with dash "-"
    
  • To specify that option has an argument, put a word describing that argument after space (or equals "=" sign) as shown below. Follow either <angular-brackets> or UPPER-CASE convention for options' arguments. You can use comma if you want to separate options. In the example below, both lines are valid, however you are recommended to stick to a single style.:

    -o FILE --output=FILE       # without comma, with "=" sign
    -i <file>, --input <file>   # with comma, without "=" sign
    
  • Use two spaces to separate options with their informal description:

    --verbose More text.   # BAD, will be treated as if verbose option had
                           # an argument "More", so use 2 spaces instead
    -q        Quit.        # GOOD
    -o FILE   Output file. # GOOD
    --stdout  Use stdout.  # GOOD, 2 spaces
    
  • If you want to set a default value for an option with an argument, put it into the option-description, in form [default: <my-default-value>]:

    --coefficient=K  The K coefficient [default: 2.95]
    --output=FILE    Output file [default: test.txt]
    --directory=DIR  Some directory [default: ./]
    
  • If the option is not repeatable, the value inside [default: ...] will be interpreted as string. If it is repeatable, it will be splited into a list on whitespace:

    Usage: my_program.py [--repeatable=<arg> --repeatable=<arg>]
                         [--another-repeatable=<arg>]...
                         [--not-repeatable=<arg>]
    
    # will be ["./here", "./there"]
    --repeatable=<arg>          [default: ./here ./there]
    
    # will be ["./here"]
    --another-repeatable=<arg>  [default: ./here]
    
    # will be "./here ./there", because it is not repeatable
    --not-repeatable=<arg>      [default: ./here ./there]
    

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 .

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
7,858
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,398
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,500
star
4

django-silk

Silky smooth profiling for Django
Python
4,210
star
5

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,765
star
6

django-taggit

Simple tagging for django
Python
3,205
star
7

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,021
star
8

django-redis

Full featured redis cache backend for Django.
Python
2,773
star
9

django-model-utils

Django model mixins and utilities.
Python
2,577
star
10

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,210
star
11

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,083
star
12

django-widget-tweaks

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.
Python
2,019
star
13

sorl-thumbnail

Thumbnails for Django
Python
1,717
star
14

django-constance

Dynamic Django settings.
Python
1,643
star
15

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,590
star
16

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,577
star
17

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,489
star
18

dj-database-url

Use Database URLs in your Django Application.
Python
1,439
star
19

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,356
star
20

django-tinymce

TinyMCE integration for Django
JavaScript
1,231
star
21

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,223
star
22

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,182
star
23

django-analytical

Analytics services for Django projects
Python
1,174
star
24

django-smart-selects

chained and grouped selects for django forms
Python
1,094
star
25

django-waffle

A feature flipper for Django
Python
1,075
star
26

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,067
star
27

django-rest-knox

Authentication Module for django rest auth
Python
1,057
star
28

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
997
star
29

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
990
star
30

django-payments

Universal payment handling for Django.
Python
964
star
31

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
942
star
32

django-nose

Django test runner using nose
Python
882
star
33

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
879
star
34

geojson

Python bindings and utilities for GeoJSON
Python
876
star
35

django-floppyforms

Full control of form rendering in the templates.
Python
836
star
36

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
825
star
37

django-avatar

A Django app for handling user avatars.
Python
797
star
38

django-formtools

A set of high-level abstractions for Django forms
Python
735
star
39

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
586
star
40

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
557
star
41

django-invitations

Generic invitations app for Django
Python
530
star
42

django-sortedm2m

A transparent sorted ManyToMany field for django.
Python
508
star
43

django-recurrence

Utility for working with recurring dates in Django.
Python
460
star
44

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
455
star
45

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
451
star
46

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
47

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
380
star
48

django-downloadview

Serve files with Django.
Python
357
star
49

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
328
star
50

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
314
star
51

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
52

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
297
star
53

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
290
star
54

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
286
star
55

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
258
star
56

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
250
star
57

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
58

django-fsm-log

Automatic logging for Django FSM
Python
235
star
59

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
210
star
60

django-celery-monitor

Celery Monitoring for Django
Python
191
star
61

django-ddp

Django/PostgreSQL implementation of the Meteor server.
Python
167
star
62

icalevents

Python module for iCal URL/file parsing and querying.
Python
153
star
63

django-voting

A generic voting application for Django
Python
93
star
64

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
89
star
65

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
66

django-redshift-backend

Redshift database backend for Django
Python
80
star
67

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
80
star
68

website

Code for the Jazzband website
Python
63
star
69

django-sorter

A helper app for sorting objects in Django templates.
Python
53
star
70

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
71

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
37
star
72

django-fernet-encrypted-fields

Python
35
star
73

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
31
star
74

help

Use this repo to get help from the roadies
27
star
75

.github

Community health and config files for Jazzband
7
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
7
star
77

admin

Some admin files for Jazzband
3
star
78

actions

Various GitHub actions for Jazzband projects
1
star