dideler
10/1/2012 - 8:21 PM

Formatted output in the terminal (using Python)

Formatted output in the terminal (using Python)

Most (or all) of these methods make use of ANSI escape sequences.

Straight-up

For example, using a dictionary:

ansi = {'underline': '\033[4m', 'bold': '\033[1m', 'end':'\033[0m'}
print '{[bold]}Hello World{[end]}'.format(ansi, ansi)

Or you can also create a class with enable/disable methods:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

print '{.HEADER}Hello World{.ENDC}'.format(bcolors, bcolors)

This will work on *NIX, MacOS, and Windows (provided you enable ansi.sys). There are ANSI codes for setting the colour, moving the cursor, and more.

Libraries

termcolor

E.g.:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')
  • has minimal Windows support

colorama

  • has Windows support!

blessings

  • no support for Windows command prompt

curses