Python: Adding Colors to Console Output
By ChatGPT, proofread by AMO
Note: In the following post, the responses are those of ChatGPT after being informed of a basic script.
In Python, the default print
function doesn’t support text coloring or special formatting such as bold text. However, you can use third-party libraries to add this functionality to your program.
A popular library for formatting text in color in the console is colorama
. You can install it using pip
:
pip install colorama
Next, here’s an example code that uses colorama to display the parameter in color:
import sys
from colorama import Fore, Style
# Check if there are enough arguments
if len(sys.argv) < 2:
print("Usage: python my_program.py parameter")
sys.exit(1)
# Retrieve the parameter
parameter = sys.argv[1]
###################################################
# Use the parameter with a specific color
colored_parameter = f"{Fore.GREEN}{parameter}{Style.RESET_ALL}"
# Display the parameter
print("The parameter is:", colored_parameter)
In this example, I use Fore.GREEN from colorama to set the text color to green. Style.RESET_ALL is used to reset the color after displaying the parameter.
After installing colorama and running this code, you should see the parameter displayed in green in the console.
Note that the appearance will depend on the terminal/console you are using, and not all terminals support colors or special formatting.