docopt

Awhile back I came across a really cool Python library for command-line interfaces called docopt. I was exposed to it through this video.

The key idea is that you define the interface for your software and then docopt automatically generates a parser for you. I’ve included an example below, but the docopt website has very good documentation.

Example todo

Imagine you want two write a simple tool that takes an input file and writes and output file and has one option to provide an int.

tool input.txt output.txt -s 8

One way to write this would be to use argparse

import argparse


def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument("input", help="The input text file", type=str)
    parser.add_argument("output", help="The input text file", type=str)
    parser.add_argument("-s", "--size", help="Integer window size", default=10, type=int)

    args = parser.parse_args()
    return args


def main():
    args = parse_args()

    # do stuff


if __name__ == '__main__':
    main()

With docopt, you can do the following

"""Usage: use_docopt.py [-s=<win>] <input> <output>

Process input and write text file output. Uses window size provided, or default of 10.

Arguments:
  input                 required input file
  output                required output file

Options:
  -h --help.            Show this screen.
  -s=<win> --size       Window size [default: 10].
"""
from docopt import docopt


def main():
    arguments = docopt(__doc__)

    # do stuff


if __name__ == '__main__':
    main()

In this case it turns out that the docopt version is a little bit longer (one line), but it’s nice that you can customize the help message very easily.

Tags: programming libraries python
Published on July 22, 2019