My goal is to use a command or anything else to change color for all text coming after the command. Something like this:
#Command to change color
change_color(red)
#Both outputs should be red
print("Hello world!")
print("Hi world")
change_color(green)
#Both outputs should be green
print("Hello world!")
print("Hi world")
I know i could use colorama or other methods but for now i didn't find a solution that works how i explained above. I want to do it like this because i need to change the output color for many lines of code.
I also tried using os.system('color a')
for green or something like this, but it changed color to red and if i try another color it doesn't work as expected, i think it's for the dark theme i use in my ide or in windows.
This Python code utilizes ANSI escape codes to change the color of text:
class TextColor:
RESET = "\033[0m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
PURPLE = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
current_color = TextColor.RESET
def change_color(color):
global current_color
if color == "red":
current_color = TextColor.RED
elif color == "green":
current_color = TextColor.GREEN
elif color == "yellow":
current_color = TextColor.YELLOW
elif color == "blue":
current_color = TextColor.BLUE
elif color == "purple":
current_color = TextColor.PURPLE
elif color == "cyan":
current_color = TextColor.CYAN
elif color == "white":
current_color = TextColor.WHITE
else:
print("Invalid color!")
def print_colored(text):
print(current_color + text + TextColor.RESET)
# Usage example:
change_color("red")
print_colored("Hello world!")
print_colored("Hi world")
change_color("green")
print_colored("Hello world!")
print_colored("Hi world")
ANSI escape codes are a set of standardized codes that allow a programmer to style the output in console and text based applications.