Reputation: 413
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"\033[{i}mAt {i} THIS happens! \033[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?
Upvotes: 5
Views: 7507
Reputation: 106
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.
Upvotes: 7
Reputation: 36802
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"))
Upvotes: 1