docopt is beautiful

I stumbled upon a very neat library created by Vladimir Keleshev (https://github.com/halst) called docopt which really comes in handy if you are working on command-line tools.

You should definitely check out the projects website at http://docopt.org/ and the video posted by Vladimir right at the top. The following example shows how easy it can be to setup a command-line tool in python.

It is possible to define “commands”, “arguments” and “options”. You can use several ways to describe those types. but I suggest you stick to one to make it as readable and intuitive as it can be.

By default any token is required in the defined usage pattern, but you can easily make each of them optional by using square brackets. What I like a lot is using pipe ” | ” with either parentheses or brackets to define a group of mutually exclusive tokens.

Docopt returns a simple dictionary containing all the relevant data. Keep in mind though that syntactic elements such as double dashes for options are contained in the keys as well.

Executing the code by

results in the following output:

Setting up default values for the options is really simple and is really nice to have. I will surely use docopt in my ongoing projects and possibly write about it again!