Python - command line interface

How to write a better command line interface with python…

Writing the Nth python shell script I found myself looking again at the documentation of argparse, A NIGHTMARE. After 15 minutes spent trying to understand how to use it I gave up.

Is in that moment that I’ve found docopt.

Docopt gives you the possibility to describe the command line interface as a string, following the “man page” format:

# -*- coding: utf-8 -*-
Usage: [options] DIRECTORY

    --debug              debug option
    --log-level=<level>  define the log level

And parse and use it with a single line:

from __future__ import print_function
from docopt import docopt

if __name__ == '__main__':
	args = docopt(__doc__)

Now you just need to call the script as ./ . --log-level=3 and it will print out a dictionary containing the options:

	'--debug': False,
 	'--log-level': '3',

In the official github repository you can find the implementation of this library for the most common languages.

Or a list of more exhaustive examples.