Detailed explanation of Python Colorama library: terminal output beautification tool
1. What is Colorama?
Coloramais a Python library used to implement cross-platform color text output in the terminal. It mainly provides the following functions:
- Add foreground color and background color to the text.
- Controls text styles (such as bold and underlined).
- Cross-platform support (Windows, Linux, and macOS).
It is especially suitable for Windows systems because by default, the Windows console does not support ANSI escape sequences, and Colorama automatically handles this compatibility issue.
2. Colorama installation
Colorama can be installed via pip:
pip install colorama
After the installation is complete, it can be used directly in a Python project.
3. Basic use of Colorama
3.1 Initialize Colorama
When using Colorama, initialization is required:
from colorama import init # Initialization (very important on Windows)init()
3.2 Add color
Colorama provides three main functional modules:
- Fore: Set the foreground color (font color) of the text.
- Back: Set the background color of the text.
- Style: Set text style.
Here is a simple example:
from colorama import Fore, Back, Style, init init() # Initialization print( + 'This is the red text') print( + 'This is the text on a green background') print( + 'This is bold text' + Style.RESET_ALL) # Restore the default styleprint('This is the default style text')
Running effect:
- The first line is in the red font.
- The second line is a green background.
- The third line is the bold font.
3.3 Restore the default style
To avoid affecting subsequent output, you can use it after each setting.Style.RESET_ALL
Reset style:
print( + "Blue Text" + Style.RESET_ALL) print("This is ordinary text")
3.4 Comprehensive Example
Here is a comprehensive example that outputs log level information in different colors:
from colorama import Fore, Style, init init() def log(message, level="INFO"): if level == "INFO": print( + "[INFO] " + Style.RESET_ALL + message) elif level == "WARNING": print( + "[WARNING] " + Style.RESET_ALL + message) elif level == "ERROR": print( + "[ERROR] " + Style.RESET_ALL + message) log("System startup successfully", "INFO") log("Insufficient disk space", "WARNING") log("Unable to connect to database", "ERROR")
Running effect:
-
[INFO]
Displayed in green. -
[WARNING]
Displayed in yellow. -
[ERROR]
Displayed in red.
4. Advanced use: combined with other libraries
4.1 Cooperation with argparse
When writing command line tools, you can combine Colorama andargparse
, realize the output of help information with color:
import argparse from colorama import Fore, Style, init init() parser = (description= + "This is a command line tool with color" + Style.RESET_ALL) parser.add_argument('--name', type=str, help= + "Please enter your name" + Style.RESET_ALL) args = parser.parse_args() print( + f"Hello, {}!" + Style.RESET_ALL)
4.2 Cooperation with logging
Colorama can be used for beautification of log formats:
import logging from colorama import Fore, init init() class ColorFormatter(): COLORS = { "DEBUG": , "INFO": , "WARNING": , "ERROR": , "CRITICAL": , } def format(self, record): color = (, "") message = super().format(record) return color + message + logger = ("color_logger") handler = () formatter = ColorFormatter("%(levelname)s: %(message)s") (formatter) (handler) () ("The system is running normally") ("Disk space is about to run out") ("Cannot access the database")
5. Colorama application scenarios
- Develop command line tools: Add colors to the output to improve the readability and user experience of the tool.
- Debugging and log output: Distinguish different types of log information, such as DEBUG, INFO, and WARNING.
- Demo effect: Quickly achieve beautiful output in the console and enhance visual effects.
6. Summary
Colorama is a powerful and easy to use terminal output beautification tool, especially for cross-platform scenarios. Using Colorama in development can make your tools more professional and friendly.
Are you using Colorama too? Or are there any other better terminal beautification solutions? Welcome to share in the comment section!
Complete code example:
from colorama import Fore, Back, Style, init init() print( + "Welcome to Colorama" + Style.RESET_ALL) print( + "This is a simple example") print( + "Text with red background" + Style.RESET_ALL) print( + "This is a diluted text" + Style.RESET_ALL)
Running effect:
- The output text has rich colors and clear styles.
The above is the detailed content of the operation example of Python using Colorama library to beautify terminal output. For more information about Python Colorama beautifying terminal output, please follow my other related articles!