When displaying the results of a Python script in the terminal, coloring the output by log level (Error, Warning, Success) makes it much easier to read.
There are two main ways to color print() output:
- Using ANSI escape sequences directly
- Using a library like Colorama
This article explains these two methods.
1. Using ANSI Escape Sequences Directly
Many terminal emulators (Linux/macOS terminal, Windows Terminal, etc.) support special control codes called ANSI escape sequences.
These start with \033[ (or \x1b[) followed by a code that specifies text color, background color, or style (like bold).
Basic Usage
Insert the control code before the text you want to change, and insert the “reset code” (\033[0m) where you want to return to normal.
# Define ANSI escape sequences as constants
class TermColors:
# --- Text Color ---
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
# --- Style ---
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# --- Reset ---
RESET = '\033[0m' # Reset everything
# Example using f-strings
print(f"{TermColors.GREEN}Success:{TermColors.RESET} File 'data.csv' processed successfully.")
print(f"{TermColors.YELLOW}{TermColors.BOLD}Warning:{TermColors.RESET} Config file not found. Using defaults.")
print(f"{TermColors.RED}Error:{TermColors.RESET} Database connection failed.")
print(f"{TermColors.BLUE}{TermColors.UNDERLINE}Ref URL:{TermColors.RESET} http://example.com/docs")
Main Control Codes
Here is a list of commonly used ANSI escape sequence codes.
| Code | Meaning | Code | Meaning |
\033[30m | Black (Text) | \033[40m | Black (Background) |
\033[31m | Red (Text) | \033[41m | Red (Background) |
\033[32m | Green (Text) | \033[42m | Green (Background) |
\033[33m | Yellow (Text) | \033[43m | Yellow (Background) |
\033[34m | Blue (Text) | \033[44m | Blue (Background) |
\033[35m | Magenta (Text) | \033[45m | Magenta (Background) |
\033[36m | Cyan (Text) | \033[46m | Cyan (Background) |
\033[37m | White (Text) | \033[47m | White (Background) |
| Code | Meaning |
\033[1m | Bold (or Bright) |
\033[4m | Underline |
\033[7m | Inverse (Swap text and background) |
\033[0m | Reset all styles |
Note: This method depends on the environment (OS and terminal). It may not work properly on older Windows Command Prompts (cmd.exe).
2. Using Colorama Library (Recommended)
To ensure colors work correctly across different operating systems, it is recommended to use a third-party library like Colorama.
Colorama wraps the process so that ANSI escape sequences work even on Windows.
1. Installation
First, install Colorama using pip.
pip install colorama
2. How to Use Colorama
You need to call init() at the beginning of your script.
Use Fore (text color), Back (background color), and Style to specify colors.
from colorama import init, Fore, Back, Style
# Call init() to enable ANSI sequences on Windows
# autoreset=True automatically resets the style after each print()
init(autoreset=True)
# Fore (Text Color)
print(Fore.CYAN + "Displaying system info.")
print(Fore.RED + "A fatal error occurred.")
# Back (Background Color)
print(Back.YELLOW + Fore.BLACK + " Note: Maintenance scheduled. ")
# Style
print(Style.BRIGHT + Fore.GREEN + "Connection test passed.")
# If autoreset=False (default), you must reset manually
init(autoreset=False)
print(Fore.MAGENTA + "This text is magenta.")
print("This text remains magenta.")
print(Style.RESET_ALL + "Resetting here.")
By using Colorama, you can color your print() output without worrying about OS differences.
Summary
Coloring terminal output helps improve script readability.
- ANSI Escape Sequences: Easy to use without libraries. Use codes like
\033[31m(Red) and reset with\033[0m. May not work in some environments. - Colorama Library: Install with
pip install colorama. Callinit()to support Windows and other platforms. Use intuitive names likeFore.RED.
Recommendation: Use Colorama for applications you share or need to run on Windows. Use ANSI sequences for simple personal scripts on Linux/macOS.
