The standard command to color the output of print in Python 3 using ANSI escape codes seems not to be functioning.
It has to do with the changes that accompany the newest versions of Python 3, I believe.
My System: Python 3.7.3, Windows 10, IDLE.
Although it works fine on Python 2.7, with Python 3.7 it simply doesn't function.
print("\033[1;32;40m Bright Green \n") in IDLE as shown in this article outputs [1;32;40m Bright Green. On the contrary this works fine on an online Python 2 parser giving a colored background.
A correction was found that on Python 3 the escape character is \x1b instead of \033. A modified expression inside the print statement such as print("\x1b[1;32;40m Bright Green \n") in IDLE outputs [1;32;40m Bright Green and no colored background.
print("\033[1;32;40m Bright Green \n") on a py file still outputs [31;1;4mHello[0mPython 3 parser print("\033[1;32;40m Bright Green \n") and it gave me [1;32;40m Bright Green.This use of ANSI escape codes is mostly offered as a solution in links.
What do I do wrong?
You need to use different code depending on if you are using terminal or IDLE. There are many ways to do it for the terminal, but for IDLE, below is the way I found.
Use sys.stdout.shell.write(to_print, color), with the variable colors being one of the strings below
You can use the below colors:
BUILTINSTRINGconsoleCOMMENTstdoutstderrhitDEFINITIONKEYWORDERRORimport sys
try:
color = sys.stdout.shell
color.write("Hi? \n","STRING")
except AttributeError:
raise RuntimeError("Use IDLE")
The python colored library works without any issues. ANSI Escape codes are not as smooth.
After pip install colored you can then after from colored import stylized
then try-
print(stylize("This is green.", colored.fg("green")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With