Using the Colorama Module in Python to Enhance Terminal Output
This article explains how to install the Python Colorama module, use its Fore, Back, and Style classes to add colors and styles to terminal output, and provides complete example code demonstrating colored and formatted CLI messages.
Colorama is a simple and effective Python module for adding colors, background colors, and style attributes to terminal output, making command‑line interfaces more readable and visually appealing.
First, install the module via pip install colorama and import the necessary classes with from colorama import Fore, Back, Style.
The module provides a range of color constants such as Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE for text, and analogous Back.* constants for background colors.
To print bold green text, for example, use:
print(Fore.GREEN + Style.BRIGHT + "Hello World!" + Style.RESET_ALL)This combines Fore.GREEN for the color and Style.BRIGHT for boldness, then resets the style with Style.RESET_ALL.
Further examples demonstrate different colors and backgrounds:
print(Fore.RED + "Error: " + Style.RESET_ALL + "Something went wrong.")
print(Fore.YELLOW + "Warning: " + Style.RESET_ALL + "This may be risky.")
print(Fore.GREEN + "Success: " + Style.RESET_ALL + "All systems are go.")
print(Back.BLUE + "Important: " + Style.RESET_ALL + "Please read this message!")Running this code produces colored messages in the terminal, improving clarity and user experience.
In conclusion, Colorama enables developers to create more user‑friendly CLI tools by adding color, background, and style effects. Below is the full example code that combines installation, imports, and several colored output statements:
from colorama import Fore, Back, Style
# 使用 Colorama 模块美化输出
print(Fore.RED + "Error: " + Style.RESET_ALL + "Something went wrong.")
print(Fore.YELLOW + "Warning: " + Style.RESET_ALL + "This may be risky.")
print(Fore.GREEN + "Success: " + Style.RESET_ALL + "All systems are go.")
print(Back.BLUE + "Important: " + Style.RESET_ALL + "Please read this message!")Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
