Shell Scripting with Python and docopt

As a Pythonista I love the expressiveness and simplicity of the Python language. So, when some of my shell scripts are getting more and more complex I have the feeling that using Python would be more precise.

Python is a mighty friend, even at the command line prompt. It also comes with some powerful friends which are helping you to write awesome shell scripts. Starting with this article I will introduce you to some of them, today there is docopt.

docopt - Command-line interface description language

Using docopt makes writing shell scripts a breeze as you have no longer to deal with argparse. docopt parses the POSIX compliant usage patterns of your script's docstring and offers you an understandable interface for accessing its arguments.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
"""
An awesome pythonic script.

Usage:
  script --opt <arg>
  script --h | --help
  script --version

Options:
  -h --help   Show this help
  --version   Show version
"""
from docopt import docopt
print(docopt(__doc__, version='1.0.0'))

Also a great deal is the fact that it encourages the author to write a documentation, even if it consists of only a handful of lines to make docopt work.

docopt is not part of the standard lib unfortunately which might stop you from using it when writing highly portable scripts.