Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 bug print background color issue

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.

  • Running print("\033[1;32;40m Bright Green \n") on a py file still outputs [31;1;4mHello[0m
  • Since there are differences between my local system I tried to run on an online Python 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?

like image 799
ExoticBirdsMerchant Avatar asked Apr 12 '26 08:04

ExoticBirdsMerchant


2 Answers

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:

  • BUILTIN
  • STRING
  • console
  • COMMENT
  • stdout
  • stderr
  • hit
  • DEFINITION
  • KEYWORD
  • ERROR
import sys

try:
    color = sys.stdout.shell
    color.write("Hi? \n","STRING")
except AttributeError:
    raise RuntimeError("Use IDLE")
like image 87
KetZoomer Avatar answered Apr 14 '26 23:04

KetZoomer


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")))


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!