VSCode: ANSI Colors in Terminal

Question:

How do I print text in ansi colors in the terminal with python?
I have this code to test what code has what effect on the text:

for i in range(0, 55):
    print(f"33[{i}mAt {i} THIS happens! 33[0m")

But all I see is:

←[0mAt 0 THIS happens! ←[0m
←[1mAt 1 THIS happens! ←[0m
←[2mAt 2 THIS happens! ←[0m
←[3mAt 3 THIS happens! ←[0m
←[4mAt 4 THIS happens! ←[0m
...

It works as intended in the online editor repl.it.

I know that there are the terminal.ansi colors in the theme settings, but how do I access them?

Asked By: Tweakimp

||

Answers:

Escape sequences will vary by terminal, and if stdout isn’t a tty, things will get weird for you.

The easiest way to print colors to the terminal without relying on these sequences is with the blessings package. The following will print hello in red and world in green (for example):

from blessings import Terminal
term = Terminal()
print(term.red("hello"), term.green("world"))
Answered By: Ryan Haining

I would use the colorama package to support ANSI sequences on Windows.

import colorama
colorama.init()

# your code with ansi sequences here

Edit: This method is platform agnostic (ANSI sequences will not be modified on terminals which support them) and allows you to use raw ANSI sequences in strings, as well as providing you with color definitions.

Answered By: Shtaiven