Docopt module in Python

The Docopt module in Python is used to create command-line interfaces. Similar to other command line arguments and options, docopt allows us to define command line arguments and options and also generate help messages and usage strings for the program. In this article, we will understand how the Docopt module is defined and how it is used to create a command line interface.

Installation

You can install the Docopt module before using it with the help of the pip command in Python. To install the Docopt module type the following command on your terminal or command prompt ?

pip install docopt

Basic Example: Simple File Reader

In the following code, we will create a simple program that takes a filename as an argument and prints its contents. The docstring at the top defines the usage pattern ?

"""Usage: simple_program.py <filename>

Print the contents of the file to the console.
"""

from docopt import docopt

def main():
    args = docopt(__doc__)
    filename = args['<filename>']
    
    try:
        with open(filename, 'r') as f:
            print(f.read())
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.")

if __name__ == '__main__':
    main()

To run this program, save it as simple_program.py and use ?

python simple_program.py test.txt

The output would be ?

This is testing the docopt module.

Program with Options

This example demonstrates a program that takes a filename as an argument and an optional flag that specifies whether or not to display line numbers. The docstring defines both the usage pattern and available options ?

"""Usage: program_with_options.py [--line-numbers] <filename>

Print the contents of the file to the console, with line numbers if specified.

Options:
  --line-numbers  Display line numbers.
"""

from docopt import docopt

def main():
    args = docopt(__doc__)
    filename = args['<filename>']
    
    try:
        with open(filename, 'r') as f:
            if args['--line-numbers']:
                for i, line in enumerate(f, 1):
                    print(f"{i}: {line}", end="")
            else:
                print(f.read())
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.")

if __name__ == '__main__':
    main()

To run this program with line numbers, use ?

python program_with_options.py --line-numbers test.txt

The output would be ?

1: This is testing the docopt module.
2: This is line 2
3: This is line 3
4: This is line 4

How Docopt Works

Docopt parses the module's docstring to understand the command-line interface. The key elements are ?

  • Usage patterns: Define how the program should be called
  • Arguments: Required parameters enclosed in <>
  • Options: Optional flags starting with -- or -
  • Help text: Descriptions for options and overall program purpose

Advanced Example: Multiple Options

Here's a more complex example with multiple options and arguments ?

"""Usage: advanced_program.py [--verbose] [--count=N] <input_file> [<output_file>]

Process a file with various options.

Options:
  --verbose        Show detailed output.
  --count=N        Process only N lines [default: 10].
  -h --help        Show this help message.
"""

from docopt import docopt

def main():
    args = docopt(__doc__)
    
    input_file = args['<input_file>']
    output_file = args['<output_file>']
    verbose = args['--verbose']
    count = int(args['--count'])
    
    if verbose:
        print(f"Processing {input_file} with count={count}")
    
    try:
        with open(input_file, 'r') as f:
            lines = f.readlines()[:count]
            
        if output_file:
            with open(output_file, 'w') as f:
                f.writelines(lines)
            if verbose:
                print(f"Written {len(lines)} lines to {output_file}")
        else:
            for line in lines:
                print(line, end="")
                
    except FileNotFoundError:
        print(f"Error: File '{input_file}' not found.")

if __name__ == '__main__':
    main()

Conclusion

The docopt module provides a declarative approach to creating command-line interfaces in Python. By defining the usage pattern in the docstring, docopt automatically handles argument parsing and help message generation. This makes it easy to create professional command-line tools with minimal code and maximum clarity.

Updated on: 2026-03-27T07:11:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements