Open In App
Related Articles

Docopt module in Python

Like Article
Save Article
Report issue
Docopt is a command line interface description module. It helps you define a interface for a command-line application and generates parser for it. The interface message in docopt is a formalized help message.


You can install docopt module in various ways, pip is one of the best ways to install docopt.
$pip install docopt
Note: docopt is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy as well.


docopt is most commonly used to display the help messages and it is invoked with -h or –help option. You can import and call this module with the following command.
from docopt import docopt
docopt(doc, argv = None, version = None,
       help = True, options = False)

Parameters of the module is as shown below :
  • doc : It is a docstring (__doc__) that contains the help message.
  • argv : It is an optional argument vector contains list of strings.
  • version : It is an optional argument mentioning the version of the program.
  • help : Responsible for displaying the help message. It is True by default.
  • options_first : This doesn’t allow the mixing of positional arguments and optional arguments. By default it is False.

Usage Pattern

docopt gives you strong control over your help page and it consists of the usage keyword which is case-insensitive that is followed by your program_name. A usage pattern can be described with various elements as mentioned below :
usage =
Usage : command --option [optional argument] --another-option =<argument> (--option1 | --option2 )  <argument>...

< argument > argument : The element starting with “<” and ending with “>” is called a positional argument. It is position sensitive. –option -o: The element starting with “–” or “-” are called as long or short option. It can either be mentioned as --option or -o.
  -h, --help     Display help
  -o, --option   Display options
  -l, --all      List all
  -q, --quit     exit
  --version      Version 3.6.1 
[optional argument] : The element starting with “[” and ending with “]” is called an optional argument. It is considered optionally. < argument >… : The ellipsis “…” is used when the element present to the left can be repeated more than once. (required arguments) : The elements starting with “(” and ending with “)” is a required element. (--option1 | --option2) says that either of –option1 or –option2 is required. Example :
# filename ='"
usage ='''
Usage:  [(<name1>|<name2>)] <name3>...  mov <name1> <name2>  (--h|--q) [<name1> -l]  --version
  -l, --all      List all.
  -q, --quit     exit.
  --version      Version 3.6.1 
  -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
args = docopt(usage)

Output :

Last Updated : 10 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Similar Reads