Search code examples
pythonterminaloutputansi-colors

Python colored text to the terminal


We can set color text or foreground color text in the terminal in Python. I have gone through this SO's answer. Some of the example color code is here

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[96m'

print(f"{bcolors.OKGREEN}Yes we can set any Hex color in terminal?{bcolors.ENDC}")

Everything is okay. But you may be noticed we have a few color codes to set. After the digging drive, I found some other color code source from Microsoft docs. I have two of my questions here.

  • What does the mean of the code like BOLD = '\033[1m' (pattern means)?
  • Can we convert/use any Hex color code in the terminal? the color source is limited so, can we use any hex code in the terminal?

Solution

  • ANSI Escape Codes

    ANSI escape codes allow you to do plenty of beautiful things in the terminal. You can change the color of the font, font style (bold, italic, underlined, etc...), and you can also move the cursor to overwrite previous text, to make text change dynamically.

    Building codes

    Basically, the codes are built like this:

    \033[XXXm
    

    where XXX is a series of semicolon-separated parameters.

    • they start with \033[ (or any of the codes specified above + [)
    • then, the contain an arbitrary number of integers separated by ;
    • and they end with m

    The code containing only 0 (being \x1B[0m) will reset any style property of the font.

    Most of the time, you will print a code changing the style of your terminal, then print a certain string, and then, the reset code.

    Here are the codes that you can use to change the color of the font, or the color of the background.

    | Color                                  | Font code        | Background code  |
    |----------------------------------------|------------------|------------------|
    | Black                                  | \x1B[30m         | \x1B[40m         |
    | Red                                    | \x1B[31m         | \x1B[41m         |
    | Green                                  | \x1B[32m         | \x1B[42m         |
    | Yellow                                 | \x1B[33m         | \x1B[43m         |
    | Blue                                   | \x1B[34m         | \x1B[44m         |
    | Magenta                                | \x1B[35m         | \x1B[45m         |
    | Cyan                                   | \x1B[36m         | \x1B[46m         |
    | White                                  | \x1B[37m         | \x1B[47m         |
    | Any palette color (with V in [0-255])  | \x1B[38;5;Vm     | \x1B[48;5;Vm     |
    | Any RGB color (with values in [0-255]) | \x1B[38;2;R;G;Bm | \x1B[48;2;R;G;Bm |