Luca Lanziani
Published

Mon 05 January 2015

←Home

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: test.py [options] DIRECTORY

Options:
    --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__)
    print(args)

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

{
    '--debug': False,
    '--log-level': '3',
    'DIRECTORY': '.'
}

In the official github repository https://github.com/docopt you can find the implementation of this library for the most common languages.

Or a list of more exhaustive examples.

Share on: TwitterFacebookGoogle+Email

Related Articles
Go Top