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.
"""Helper to process image files in a an arbitrary nested
directory structure. In addition to common tasks, operations
such as thumbnail creation are supported.
helper.py (resize|crop) <src> <dest> <width> <height>
helper.py createThumbs <src> <dest> [-s <size>]
helper.py -h | --help
<src> Directory which shall be processed
<dest> Path where the resulting directory shall be created
<width> The desired width of the image(s)
<height> The desired height of the image(s)
<size> The desired size of the thumbnails
-h --help Show help message
-s <size> Specify width and height of the thumbnails [default: 128]
from docopt import docopt
from pprint import pprint
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
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
python helper.py crop media mediaCropped 640 480
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!