Source

colorin / colorin / cli.py

Full commit
# -----------------------------------------------------------------------------
# Copyright:  (c) 2013 Felipe Lopez, aka sirgazil
# e-mail:     felipe.lopac@gmail.com
# License:    http://creativecommons.org/publicdomain/zero/1.0/
#
#             Put in the public domain. You may use, modify and share
#             this program under the Creative Commons Zero legal code.
# -----------------------------------------------------------------------------

"""Command line interface utilities.

This module provides some classes to format, color and control text
output in text terminals using ANSI escape sequences.

For more information `read about ANSI escape sequences <http://en.wikipedia.org/wiki/ANSI_escape_code>`_.

"""

import sys


class Display(object):
    """Represent the terminal screen.

    Instances of this class provide the main methods for manipulating
    cursor position, erase the screen, update and append output and
    display mode such as forground and background colors.

    """    
    def __init__(self):
        """Initialize the object."""
        pass

    def bold(self, string):
        """Print a bold string."""
        self.turn_bold()
        print(string)
        self.turn_fx_off()

    def color(self, string, fg_color="White", bg_color="", bold=False):
        """Print a colored string."""
        self.set_fg_color(fg_color)
        self.set_bg_color(bg_color)
        if bold:
            self.turn_bold()
        print(string)
        self.turn_fx_off()

    def turn_bold(self):
        """Turn all new text output bold.
        
        Text will be displayed bold until the turn_fx_off() function is
        called.
        
        """
        sys.stdout.write("\033[1m")

    def turn_fx_off(self):
        """Turn all attributes off."""
        sys.stdout.write("\033[0m")

    def erase(self):
        """Erase display.

        Clear the screen and move the cursor to the home position
        (line 0, column 0).

        """
        sys.stdout.write("\033[2J")

    def set_fg_color(self, color):
        """Set forground color.

        Parameters:

        color (str) -- The name of the color. It can be Black, Red,
        Green, Yellow, Blue, Magenta, Cyan and White.

        """
        colors = {"Black": 30, "Red": 31, "Green": 32, "Yellow": 33,
                  "Blue": 34, "Magenta": 35, "Cyan": 36, "White": 37}

        if color in colors:
            sys.stdout.write("\033[{0}m".format(colors[color]))

    def set_bg_color(self, color):
        """Set background color.

        Parameters:

        color (str) -- The name of the color. It can be Black, Red,
        Green, Yellow, Blue, Magenta, Cyan and White.

        """
        colors = {"Black": 40, "Red": 41, "Green": 42, "Yellow": 43,
                  "Blue": 44, "Magenta": 45, "Cyan": 46, "White": 47}

        if color in colors:
            sys.stdout.write("\033[{0}m".format(colors[color]))