couleur en console avec python

Note

il faut utiliser http://code.google.com/p/colorconsole ou voir l’utilisation de https://pypi.python.org/pypi/termcolor apriori plus simple

Windows

Voici un module permettant d’avoir une sortie console avec un gestion des couleurs de:

  • foreground
  • background

le module color_console.py

"""
Colors text in console mode application (win32).
Uses ctypes and Win32 methods SetConsoleTextAttribute and
GetConsoleScreenBufferInfo.

$Id: color_console.py 534 2009-05-10 04:00:59Z andre $
"""

from ctypes import windll, Structure, c_short, c_ushort, byref

SHORT = c_short
WORD = c_ushort

class COORD(Structure):
    """struct in wincon.h."""
    _fields_ = [
        ("X", SHORT),
        ("Y", SHORT)]

class SMALL_RECT(Structure):
    """struct in wincon.h."""
    _fields_ = [
        ("Left", SHORT),
        ("Top", SHORT),
        ("Right", SHORT),
        ("Bottom", SHORT)]

class CONSOLE_SCREEN_BUFFER_INFO(Structure):
    """struct in wincon.h."""
    _fields_ = [
        ("dwSize", COORD),
        ("dwCursorPosition", COORD),
        ("wAttributes", WORD),
        ("srWindow", SMALL_RECT),
        ("dwMaximumWindowSize", COORD)]

# winbase.h
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12

# wincon.h
FOREGROUND_BLACK         = 0x0000
FOREGROUND_BLUE            = 0x0001
FOREGROUND_GREEN         = 0x0002
FOREGROUND_CYAN            = 0x0003
FOREGROUND_RED             = 0x0004
FOREGROUND_MAGENTA     = 0x0005
FOREGROUND_YELLOW        = 0x0006
FOREGROUND_GREY            = 0x0007
FOREGROUND_INTENSITY = 0x0008 # foreground color is intensified.

BACKGROUND_BLACK         = 0x0000
BACKGROUND_BLUE            = 0x0010
BACKGROUND_GREEN         = 0x0020
BACKGROUND_CYAN            = 0x0030
BACKGROUND_RED             = 0x0040
BACKGROUND_MAGENTA     = 0x0050
BACKGROUND_YELLOW        = 0x0060
BACKGROUND_GREY            = 0x0070
BACKGROUND_INTENSITY = 0x0080 # background color is intensified.

stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo

def get_text_attr():
    """Returns the character attributes (colors) of the console screen
    buffer."""
    csbi = CONSOLE_SCREEN_BUFFER_INFO()
    GetConsoleScreenBufferInfo(stdout_handle, byref(csbi))
    return csbi.wAttributes

def set_text_attr(color):
    """Sets the character attributes (colors) of the console screen
    buffer. Color is a combination of foreground and background color,
    foreground and background intensity."""
    SetConsoleTextAttribute(stdout_handle, color)


import sys

def test():
    """Simple Pyton 3.0 test for color_console."""
    default_colors = get_text_attr()
    default_bg = default_colors & 0x0070
    default_fg = default_colors & 0x0007
    set_text_attr(FOREGROUND_GREEN | default_bg | FOREGROUND_INTENSITY)
    print('===========================================')
    set_text_attr(FOREGROUND_BLUE | BACKGROUND_GREY | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY)
    print('And Now for Something', end=' ')
    sys.stdout.flush() # Force writing first part of the line in blue
    set_text_attr(FOREGROUND_RED | BACKGROUND_GREY | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY)
    print('Completely Different!')
    set_text_attr(default_colors)
    set_text_attr(FOREGROUND_RED | default_bg | FOREGROUND_INTENSITY)
    print('===========================================')
    set_text_attr(default_colors)

if __name__ == "__main__":
  test()

On peut le retrouver sur le lien http://www.burgaud.com/bring-colors-to-the-windows-console-with-python/

Il existe aussi un module qui gère la coloration directement au niveau du terminal

http://code.google.com/p/colorconsole

Il existe a prior un module multiplateforme https://pypi.python.org/pypi/colorama

Linux

on doit lancer avec le print des caractères invisibles exemple non testé

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(bcolors.WARNING + "Warning: No active frommets remain. Continue?"+ bcolors.ENDC)

Il existe a prior un module multiplateforme https://pypi.python.org/pypi/colorama