Create a python cli program with docopt

in #utopian-io7 years ago (edited)

What Will I Learn?

  • You will learn what is docopt
  • You will learn how to use docopt
  • You will learn a common mistake when using docopt

Requirements

  • have experience in python
  • have installed python and pip

Difficulty

  • Intermediate

Tutorial Contents

What is docopt

Docopt is a python package which helps you define the interface for your command-line app and automatically generate a parser for it.docopt is available in numerous programming languages, including Go,Julia,Rust and so on.

Install Docopt

We can use pip to install this package.

pip install docopt
A simple demo of docopt

We create a file named demo.py

# !/usr/bin/env python
# --*--coding:utf-8--*--

"""DEMO CLI

Usage:
demo.py command --option1 --option2 <op2>
demo.py -h|--help
demo.py -v|--version

Options:
-h --help  Show this screen.
-v --version  Show version.
--option1  option1
--option2  option2
"""

from docopt import docopt

def demo():
    arguments = docopt(__doc__, version='DEMO 1.0')
    print(arguments)


if __name__ == '__main__':
    demo()

Then we run three commands:

  • help:
python demo.py -h

help

  • version:
python demo.py -v

version

  • common usage:
python demo.py command --option1 --option2 op2

commonusage

  • undefined usage:
python demo.py command2

undefinedusage

As we can see from the results, docopt will only run correctly if you type in the command you have defined in your source code. Otherwise, it will return you the correct usage of the program.

How docopt works

As we can see the result of common usage, arguments is a dictionary or a json.

{'--help': False,
 '--option1': True,
 '--option2': True,
 '--version': False,
 '<op2>': 'op2',
 'command': True}

The value of options or commands like '--option1' or 'command' is a boolean value. The value of a variable is a string value.
The dictionary is the result of the docopt parser. You can write your program based on this dictionary.

A common mistake when using docopt

When you encounter the error like "docopt.DocoptLanguageError: unmatched '('
" or "docopt.DocoptLanguageError: unmatched '['
",
error
you must check your Options definition. The separator between option and explaination must be two spaces instead of one.
Error example:

-h --help Show this screen.

Correct example:

-h --help  Show this screen.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

Your tutorial consists pretty much "copy paste this" that we do not like.

You can contact us on Discord.
[utopian-moderator]

Sorry, I don't know what "copy paste this" means. Was my posting considered as plagiarism? or there are too much "copy the code you can get the result"?