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.
We can use pip to install this package.
pip install docopt
We create a file named demo.py
# !/usr/bin/env python
# --*--coding:utf-8--*--
"""DEMO CLI
Usage:
demo.py command --option1 --option2
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:
python demo.py -h
python demo.py -v
python demo.py command --option1 --option2 op2
python demo.py command2
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.
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',
'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.
When you encounter the error like "docopt.DocoptLanguageError: unmatched '('
" or "docopt.DocoptLanguageError: unmatched '['
",
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.