Python Colorama Module
colorama makes ANSI escape character sequences (for producing colored terminal text and cursor positioning) work under MS Windows. On other platforms, it simply passes the ANSI codes through.
Installation
pip install colorama
Initialization
It is important to call init() at the start of your script. This converts ANSI sequences to Windows API calls on Windows.
from colorama import init
# autoreset=True automatically resets colors after each print statement
init(autoreset=True)
Basic Usage
Colorama provides three main classes: Fore (foreground), Back (background), and Style.
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
Available Constants
- Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
- Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
- Style: DIM, NORMAL, BRIGHT, RESET_ALL.
Cursor Positioning
Colorama also supports moving the cursor.
from colorama import Cursor
# Move cursor up 2 lines
print(Cursor.UP(2))
# Move cursor to specific position (x, y)
print(Cursor.POS(10, 5) + "Text at 10, 5")
De-initialization
To stop using colorama and restore stdout/stderr to their original state:
from colorama import deinit
deinit()