Package: blessings
Coding with Blessings looks like this…from blessings import Terminal

t = Terminal()

print t.bold('Hi there!')
print t.bold_red_on_bright_green('It hurts my eyes!')

with t.location(0, t.height - 1):
    print 'This is at the bottom.'Or, for byte-level control, you can drop down and play with raw terminal
capabilities:print '{t.bold}All your {t.red}bold and red base{t.normal}'.format(t=t)
print t.wingo(2)Full API ReferenceThe PitchBlessings lifts several ofcurses’ limiting assumptions, and it makes your
code pretty, too:Use styles, color, and maybe a little positioning without necessarily
clearing the whole
screen first.Leave more than one screenful of scrollback in the buffer after your program
exits, like a well-behaved command-line app should.Get rid of all those noisy, C-like calls totigetstrandtparm, so
your code doesn’t get crowded out by terminal bookkeeping.Act intelligently when somebody redirects your output to a file, omitting the
terminal control codes the user doesn’t want to see (optional).Before And AfterWithout Blessings, this is how you’d print some underlined text at the bottom
of the screen:from curses import tigetstr, setupterm, tparm
from fcntl import ioctl
from os import isatty
import struct
import sys
from termios import TIOCGWINSZ

# If we want to tolerate having our output piped to other commands or
# files without crashing, we need to do all this branching:
if hasattr(sys.stdout, 'fileno') and isatty(sys.stdout.fileno()):
    setupterm()
    sc = tigetstr('sc')
    cup = tigetstr('cup')
    rc = tigetstr('rc')
    underline = tigetstr('smul')
    normal = tigetstr('sgr0')
else:
    sc = cup = rc = underline = normal = ''
print sc  # Save cursor position.
if cup:
    # tigetnum('lines') doesn't always update promptly, hence this:
    height = struct.unpack('hhhh', ioctl(0, TIOCGWINSZ, '\000' * 8))[0]
    print tparm(cup, height - 1, 0)  # Move cursor to bottom.
print 'This is {under}underlined{normal}!'.format(under=underline,
                                                  normal=normal)
print rc  # Restore cursor position.That was long and full of incomprehensible trash! Let’s try it again, this time
with Blessings:from blessings import Terminal

term = Terminal()
with term.location(0, term.height - 1):
    print 'This is', term.underline('pretty!')Much better.What It ProvidesBlessings provides just one top-level object:Terminal. Instantiating aTerminalfigures out whether you’re on a terminal at all and, if so, does
any necessary terminal setup. After that, you can proceed to ask it all sorts
of things about the terminal. Terminal terminal terminal.Simple FormattingLots of handy formatting codes (“capabilities” in low-level parlance) are
available as attributes on aTerminal. For example:from blessings import Terminal

term = Terminal()
print 'I am ' + term.bold + 'bold' + term.normal + '!'Though they are strings at heart, you can also use them as callable wrappers so
you don’t have to saynormalafterward:print 'I am', term.bold('bold') + '!'Or, if you want fine-grained control while maintaining some semblance of
brevity, you can combine it with Python’s string formatting, which makes
attributes easy to access:print 'All your {t.red}base {t.underline}are belong to us{t.normal}'.format(t=term)Simple capabilities of interest include…boldreverseunderlineno_underline(which turns off underlining)blinknormal(which turns off everything, even colors)Here are a few more which are less likely to work on all terminals:dimitalicandno_italicshadowandno_shadowstandoutandno_standoutsubscriptandno_subscriptsuperscriptandno_superscriptflash(which flashes the screen once)Note that, while the inverse ofunderlineisno_underline, the only way
to turn offboldorreverseisnormal, which also cancels any
custom colors. This is because there’s no portable way to tell the terminal to
undo certain pieces of formatting, even at the lowest level.You might also notice that the above aren’t the typical incomprehensible
terminfo capability names; we alias a few of the harder-to-remember ones for
readability. However, you aren’t limited to these: you can reference any
string-returning capability listed on theterminfo man pageby the name
under the “Cap-name” column: for example,term.rum.Color16 colors, both foreground and background, are available as easy-to-remember
attributes:from blessings import Terminal

term = Terminal()
print term.red + term.on_green + 'Red on green? Ick!' + term.normal
print term.bright_red + term.on_bright_blue + 'This is even worse!' + term.normalYou can also call them as wrappers, which sets everything back to normal at the
end:print term.red_on_green('Red on green? Ick!')
print term.yellow('I can barely see it.')The available colors are…blackredgreenyellowbluemagentacyanwhiteYou can set the background color instead of the foreground by prependingon_, as inon_blue. There is also abrightversion of each color:
for example,on_bright_blue.There is also a numerical interface to colors, which takes an integer from
0-15:term.color(5) + 'Hello' + term.normal
term.on_color(3) + 'Hello' + term.normal

term.color(5)('Hello')
term.on_color(3)('Hello')If some color is unsupported (for instance, if only the normal colors are
available, not the bright ones), trying to use it will, on most terminals, have
no effect: the foreground and background colors will stay as they were. You can
get fancy and do different things depending on the supported colors by checkingnumber_of_colors.Compound FormattingIf you want to do lots of crazy formatting all at once, you can just mash it
all together:from blessings import Terminal

term = Terminal()
print term.bold_underline_green_on_yellow + 'Woo' + term.normalOr you can use your newly coined attribute as a wrapper, which implicitly sets
everything back to normal afterward:print term.bold_underline_green_on_yellow('Woo')This compound notation comes in handy if you want to allow users to customize
the formatting of your app: just have them pass in a format specifier like
“bold_green” on the command line, and do a quickgetattr(term,that_option)('Yourtext')when you do your formatting.I’d be remiss if I didn’t creditcouleur, where I probably got the idea for
all this mashing.Moving The CursorWhen you want to move the cursor to output text at a specific spot, you have
a few choices.Moving TemporarilyMost often, you’ll need to flit to a certain location, print something, and
then return: for example, when updating a progress bar at the bottom of the
screen.Terminalprovides a context manager for doing this concisely:from blessings import Terminal

term = Terminal()
with term.location(0, term.height - 1):
    print 'Here is the bottom.'
print 'This is back where I came from.'Parameters tolocation()arexand theny, but you can also pass
just one of them, leaving the other alone. For example…with term.location(y=10):
    print 'We changed just the row.'If you’re doing a series ofmovecalls (see below) and want to return the
cursor to its original position afterward, calllocation()with no
arguments, and it will do only the position restoring:with term.location():
    print term.move(1, 1) + 'Hi'
    print term.move(9, 9) + 'Mom'Note that, sincelocation()uses the terminal’s built-in
position-remembering machinery, you can’t usefully nest multiple calls. Uselocation()at the outermost spot, and use simpler things likemoveinside.Moving PermanentlyIf you just want to move and aren’t worried about returning, do something like
this:from blessings import Terminal

term = Terminal()
print term.move(10, 1) + 'Hi, mom!'movePosition the cursor elsewhere. Parameters are y coordinate, then x
coordinate.move_xMove the cursor to the given column.move_yMove the cursor to the given row.How does all this work? These are simply more terminal capabilities, wrapped to
give them nicer names. The added wrinkle–that they take parameters–is also
given a pleasant treatment: rather than making you dig uptparm()all the
time, we simply make these capabilities into callable strings. You’d get the
raw capability strings if you were to just print them, but they’re fully
parametrized if you pass params to them as if they were functions.Consequently, you can also reference any other string-returning capability
listed on theterminfo man pageby its name under the “Cap-name” column.One-Notch MovementFinally, there are some parameterless movement capabilities that move the
cursor one character in various directions:move_leftmove_rightmove_upmove_downFor example…print term.move_up + 'Howdy!'Height And WidthIt’s simple to get the height and width of the terminal, in characters:from blessings import Terminal

term = Terminal()
height = term.height
width = term.widthThese are newly updated each time you ask for them, so they’re safe to use from
SIGWINCH handlers.Clearing The ScreenBlessings provides syntactic sugar over some screen-clearing capabilities:clearClear the whole screen.clear_eolClear to the end of the line.clear_bolClear backward to the beginning of the line.clear_eosClear to the end of screen.Full-Screen ModePerhaps you have seen a full-screen program, such as an editor, restore the
exact previous state of the terminal upon exiting, including, for example, the
command-line prompt from which it was launched. Curses pretty much forces you
into this behavior, but Blessings makes it optional. If you want to do the
state-restoration thing, use these capabilities:enter_fullscreenSwitch to the terminal mode where full-screen output is sanctioned. Print
this before you do any output.exit_fullscreenSwitch back to normal mode, restoring the exact state from beforeenter_fullscreenwas used.Usingexit_fullscreenwill wipe away any trace of your program’s output, so
reserve it for when you don’t want to leave anything behind in the scrollback.There’s also a context manager you can use as a shortcut:from blessings import Terminal

term = Terminal()
with term.fullscreen():
    # Print some stuff.Besides brevity, another advantage is that it switches back to normal mode even
if an exception is raised in thewithblock.Pipe SavvyIf your program isn’t attached to a terminal, like if it’s being piped to
another command or redirected to a file, all the capability attributes onTerminalwill return empty strings. You’ll get a nice-looking file without
any formatting codes gumming up the works.If you want to override this–like if you anticipate your program being piped
throughless-r, which handles terminal escapes just fine–passforce_styling=Trueto theTerminalconstructor.In any case, there is adoes_stylingattribute onTerminalthat lets
you see whether your capabilities will return actual, working formatting codes.
If it’s false, you should refrain from drawing progress bars and other frippery
and just stick to content, since you’re apparently headed into a pipe:from blessings import Terminal

term = Terminal()
if term.does_styling:
    with term.location(0, term.height - 1):
        print 'Progress: [=======>   ]'
print term.bold('Important stuff')Shopping ListThere are decades of legacy tied up in terminal interaction, so attention to
detail and behavior in edge cases make a difference. Here are some ways
Blessings has your back:Uses the terminfo database so it works with any terminal typeProvides up-to-the-moment terminal height and width, so you can respond to
terminal size changes (SIGWINCH signals). (Most other libraries query theCOLUMNSandLINESenvironment variables or thecolsorlinesterminal capabilities, which don’t update promptly, if at all.)Avoids making a mess if the output gets piped to a non-terminalWorks great with standard Python string templatingProvides convenient access to all terminal capabilities, not just a sugared
fewOutputs to any file-like object, not just stdoutKeeps a minimum of internal state, so you can feel free to mix and match with
calls to curses or whatever other terminal libraries you likeBlessings does not provide…Native color support on the Windows command prompt. However, it should work
when used in concert withcolorama.BugsBugs or suggestions? Visit theissue tracker.Blessings tests are run automatically byTravis CI.LicenseBlessings is under the MIT License. See the LICENSE file.Version History1.7Drop support for Python 2.6 and 3.3, which are end-of-lifed.Switch from 2to3 to thesixlibrary.1.6.1Don’t crash ifnumber_of_colors()is called when run in a non-terminal
or whendoes_stylingis otherwise false.1.6Adddoes_stylingproperty. This takesforce_stylinginto account
and should replace most uses ofis_a_tty.Makeis_a_ttya read-only property, likedoes_styling. Writing to
it never would have done anything constructive.Addfullscreen()andhidden_cursor()to the auto-generated docs.Fall back toLINESandCOLUMNSenvironment vars to find height and
width. (jquast)Support terminal types, such as kermit and avatar, that use bytes 127-255
in their escape sequences. (jquast)1.5.1Clean up fabfile, removing the redundanttestcommand.Add Travis support.Makepython setup.py testwork without spurious errors on 2.6.Work around a tox parsing bug in its config file.Make context managers clean up after themselves even if there’s an
exception. (Vitja Makarov)Parametrizing a capability no longer crashes when there is no tty. (Vitja
Makarov)1.5Add syntactic sugar and documentation forenter_fullscreenandexit_fullscreen.Add context managersfullscreen()andhidden_cursor().Now you can force aTerminalnever to emit styles by passingforce_styling=None.1.4Add syntactic sugar for cursor visibility control and single-space-movement
capabilities.Endorse thelocation()idiom for restoring cursor position after a
series of manual movements.Fix a bug in whichlocation()wouldn’t do anything when passed zeroes.Allow tests to be run withpython setup.py test.1.3Addednumber_of_colors, which tells you how many colors the terminal
supports.Madecolor(n)andon_color(n)callable to wrap a string, like the
named colors can. Also, make them both fall back to thesetfandsetbcapabilities (like the named colors do) if the ANSIsetafandsetabaren’t available.Allowedcolorattr to act as an unparametrized string, not just a
callable.Madeheightandwidthexamine any passed-in stream before falling
back to stdout. (This rarely if ever affects actual behavior; it’s mostly
philosophical.)Made caching simpler and slightly more efficient.Got rid of a reference cycle between Terminals and FormattingStrings.Updated docs to reflect that terminal addressing (as inlocation()) is
0-based.1.2Added support for Python 3! We need 3.2.3 or greater, because the curses
library couldn’t decide whether to accept strs or bytes before that
(http://bugs.python.org/issue10570).Everything that comes out of the library is now unicode. This lets us
support Python 3 without making a mess of the code, and Python 2 should
continue to work unless you were testing types (and badly). Please file a
bug if this causes trouble for you.Changed to the MIT License for better world domination.Added Sphinx docs.1.1Added nicely named attributes for colors.Introduced compound formatting.Added wrapper behavior for styling and colors.Let you force capabilities to be non-empty, even if the output stream is
not a terminal.Added theis_a_ttyattribute for telling whether the output stream is a
terminal.Sugared the remaining interesting string capabilities.Letlocation()operate on just an xory coordinate.1.0Extracted Blessings from nose-progressive, myprogress-bar-having,
traceback-shortcutting, rootin’, tootin’ testrunner. It provided the
tootin’ functionality.