Changing Color of Command Line Output in Python Without Using Packages
Changing Color of Command Line Output in Python Without Using Packages
In Python, we often need to print output in the command line interface. While the default text color is usually sufficient, there may be situations where you want to add a touch of color to your output to improve readability or highlight certain information.
Fortunately, you can change the color of command line output in Python without relying on any external packages. In this blog post, we will explore how you can achieve this.
import sys
def print_color(text, color):
colors = {
'red': ' 33[91m',
'green': ' 33[92m',
'yellow': ' 33[93m',
'blue': ' 33[94m',
'purple': ' 33[95m',
'cyan': ' 33[96m',
'white': ' 33[97m',
'reset': ' 33[0m'
}
if color not in colors:
color = 'reset'
sys.stdout.write(f"{colors[color]}{text}{colors['reset']}")
This simple print_color function takes two arguments: the text to be printed and the color in which you want to display the text. It uses ANSI escape codes to change the text color in the terminal.
You can use this function to print messages in different colors based on the situation. For example:
print_color("Error: File not found", 'red')
print_color("Success: Operation completed", 'green')
By incorporating color-coded output into your Python scripts, you can enhance the user experience and draw attention to critical information.
Experiment with different colors and formatting options to create visually appealing and informative command line output in Python.