Sunday, August 19, 2012

Blessings, curses-like Python library

By Vasudev Ram


Blessings is a Python library that serves much the same purpose as curses (a text-mode "GUI" library for UNIX / Linux), while claiming to remove some of the limitations of curses and also result in shorter and clearer code. Example:

Blessings code for printing some underlined text at the bottom of the screen:
from blessings import Terminal

term = Terminal()
with term.location(0, term.height - 1):
    print 'This is', term.underline('pretty!')
The corresponding curses code is somewhat longer. See the Blessings site above for that code, and to download, etc.

One interesting point is that it seems to use a Python language feature to create "callable strings".

Another cool and useful feature is that it can save the state of the terminal, when your Blessings program starts, and restore it when it exits.

I remember writing a curses program in C some time ago, where I implemented similar functionality, but had to save the terminal state manually (through code) on startup, and restore it, again manually, in a SIGINT (i.e. for Ctrl-C) signal handler.

Blessings can save and restore the terminal state very simply, with calls to two "capabilities":
enter_fullscreen
and
exit_fullscreen

There is also a shortcut for the above:
from blessings import Terminal

term = Terminal()
with term.fullscreen():
    # Print some stuff.

Like my signal handler, the above code also works even if the with block raises an exception.

- Vasudev Ram - Dancing Bison Enterprises



No comments: