How do I print colored text to the terminal?
Solution 1
This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:
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[4m'
To use code like this, you can do something like:
print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)
Or, with Python 3.6+:
print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")
This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.
If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.
If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".
Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).
The Text Mode Demo Contest has more resources for doing graphics in text mode.
Solution 2
There is also the Python termcolor module. Usage is pretty simple:
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
Or in Python 3:
print(colored('hello', 'red'), colored('world', 'green'))
It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...
To get the ANSI codes working on windows, first run
os.system('color')
Solution 3
The answer is Colorama for all cross-platform coloring in Python.
It supports Python 3.5+ as well as Python 2.7.
And as of January 2021 it is maintained.
Example Code:
from colorama import Fore
from colorama import Style
print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")
Solution 4
Print a string that starts a color/style, then the string, and then end the color/style change with '\x1b[0m'
:
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
Get a table of format options for shell text with the following code:
def print_format_table():
"""
prints table of formatted text format options
"""
for style in range(8):
for fg in range(30,38):
s1 = ''
for bg in range(40,48):
format = ';'.join([str(style), str(fg), str(bg)])
s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
print(s1)
print('\n')
print_format_table()
Light-on-dark example (complete)
Dark-on-light example (partial)
Reference: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
Solution 5
Define a string that starts a color and a string that ends the color. Then print your text with the start string at the front and the end string at the end.
CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)
This produces the following in Bash, in urxvt
with a Zenburn-style color scheme:
Through experimentation, we can get more colors:
Note: \33[5m
and \33[6m
are blinking.
This way we can create a full color collection:
CEND = '\33[0m'
CBOLD = '\33[1m'
CITALIC = '\33[3m'
CURL = '\33[4m'
CBLINK = '\33[5m'
CBLINK2 = '\33[6m'
CSELECTED = '\33[7m'
CBLACK = '\33[30m'
CRED = '\33[31m'
CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE = '\33[36m'
CWHITE = '\33[37m'
CBLACKBG = '\33[40m'
CREDBG = '\33[41m'
CGREENBG = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG = '\33[46m'
CWHITEBG = '\33[47m'
CGREY = '\33[90m'
CRED2 = '\33[91m'
CGREEN2 = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2 = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2 = '\33[96m'
CWHITE2 = '\33[97m'
CGREYBG = '\33[100m'
CREDBG2 = '\33[101m'
CGREENBG2 = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2 = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2 = '\33[106m'
CWHITEBG2 = '\33[107m'
Here is the code to generate the test:
x = 0
for i in range(24):
colors = ""
for j in range(5):
code = str(x+j)
colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
print(colors)
x = x + 5
aboSamoor
Updated on May 04, 2022Comments
-
aboSamoor about 2 years
How can I output colored text to the terminal in Python?
-
Samie Bencherif over 10 yearsThis symbol would make a great colored block:
█
Only problem is that it is extended ASCII, maybe you could get it to work usinghttp://stackoverflow.com/questions/8465226/using-extended-ascii-codes-with-python
-
ayke over 10 yearsSome terminals also can display Unicode characters. If that is true for your terminal, the possible characters are almost unlimited.
-
ArtOfWarfare over 10 yearsThis answer came fairly late, but it seems to be the best to me... the ones voted above it require special hacks for Windows whereas this one just works: stackoverflow.com/a/3332860/901641
-
alvas over 7 yearsHow about stackoverflow.com/a/42528796/610569 using pypi.python.org/pypi/lazyme ? (disclaimer: shameless plug)
-
Benyamin Jafari - aGn over 3 yearsIf you don't want to install an extra package, follow this new answer.
-
-
nosklo almost 15 years@Sorin Sbarnea: Accordingly to python curses official documentation in docs.python.org/library/curses.html , the curses module is not supported on windows. Maybe you got this error instead of "No Such Module" or something like this, because you probably named your test file "curses.py" so it is importing itself.
-
Jonathan Hartley almost 14 yearsAs the author of Colorama, thanks for the mention @nbv4. I'll try and clarify a bit: Colorama aims to let Python programs print colored terminal text on all platforms, using the same ANSI codes as described in many other answers on this page. On Windows, Colorama strips these ANSI characters from stdout and converts them into equivalent win32 calls for colored text. On other platforms, Colorama does nothing. Hence you can use ANSI codes, or modules like Termcolor, and with Colorama, they 'just work' on all platforms. Is that idea, anyhow.
-
Phil P almost 13 yearsSince it's emitting ANSI codes, does it work on Windows (DOS consoles) if ansi.sys is loaded? support.microsoft.com/kb/101875
-
Alexander Tsepkov over 12 yearsJust noticed that as of 13/01/2011, it's now under MIT license
-
Adobe almost 12 yearsBut suppose my default prompt is not black - do You think it's possible to make python resotre after these tricks?
-
Dennis over 11 yearsAnother useful one is
UNDERLINE = '\033[4m'
. What happens ifansi.sys
is disabled on Windows and you try to use these ANSI escape sequences? -
Martin Ueding over 11 yearsOn Linux, you might want to use
tput
, like so since it results in more portable code. -
Demolishun over 11 years@Jonathan, This is truly an awesome library! The ability to cross platform color Python output is really really nice and useful. I am providing tools for a library that colors its own console. I can redirect the output of that console to the terminal and colorize the output. Now I can even one up the library and let the user select colors. This will allow color blind people to set things to work so they can actually see the output correctly. Thanks
-
LtWorf over 11 yearsPutting the color as a function name and not as a parameter is a questionable practice.
-
pragmatic over 11 yearsMore on this can be found here- linux.byexamples.com/archives/184/…
-
daviewales about 11 yearsThis should be in the standard library... Cross platform colour support is important, I think.
-
Janus Troelsen almost 11 yearsdoesn't have unittests (unlike colorama) and not updated since 2011
-
Tom over 10 yearsTried out colorama, used
print(Style.BRIGHT + "Header Test")
andprint (Style.DIM + word)
to create a really nice prompt. -
Evgeni Sergeev over 10 yearsTry
def d(*v): return '\x1B['+';'.join(map(str, v))+'m'
thenprint ' '.join([d(k,i)+str(i%10)+d(0) for i in range(30,38)+range(40,48) for k in range(2)])
-
dashesy over 10 yearsthis works in most shells as well as ipython, good enough for most applications
-
Sebastian Mach about 10 years@Cawas: A real use case for
disable
is when you pipe the output to a file; while tools likecat
may support colors, it is generally better to not print color information to files. -
cregox about 10 years@phresnel I see... If so I believe for this answer it should not even be mentioned as it only confuses the objectivity of it. Even if it was Steven Oxley's usage case (from the previous comment addressing this same issue) it's still the same matter. Maybe I should suggest an edit.
-
jfs about 10 years@LtWorf: you could easily make it a parameter using
getattr
if you need it. Or more likely, just create the format string dynamically instead. -
Ethan Bierlein about 10 years@joeld is it possible to do variants of one color?
-
ereOn over 9 yearsThere is also chromalog which has the ability to detect the color-capability of the displaying terminal (and to eventually fall back to other decoration methods if needed). (Disclaimer: I'm the author)
-
Floyd about 9 yearsNot very nice code, it even contains a reference to pythonw.exe ;)
-
dtk about 9 years
-
Admin almost 9 yearsWhat is the difference between the \033[ and the \x1b[ ? They seem to do the same thing
-
mike almost 9 yearsJust noting: The Python Curses module is also available in Python 3 docs.python.org/3/howto/curses.html
-
Jonathan Hartley almost 9 yearsPersonally I think that the 'curses' library has been totally eclipsed by 'blessings', in the same way 'requests' has eclipsed 'urllib', etc.
-
mike3996 over 8 years@LtWorf: why? Python's functions and methods are first-class citizens
-
LtWorf over 8 years@progo the fact that you can do it doesn't mean that you should do it. It's more generic if the colour is a parameter that you can just pass.
-
akxlr over 8 years
termcolor.COLORS
gives you a list of colours -
MaxNoe over 8 yearsYou
can just pass
a python function. -
cat over 8 yearsThis will need to change to use
contextlib
for Py3. -
Janus Troelsen over 8 years@cat: From what version of Python will that be necessary?
-
cat over 8 yearsI believe 3 and up -- it should have a
@contextlib.contextmanager
decorator on it, no? -
Janus Troelsen over 8 years@cat: Why? Works great without.
-
gustafbstrom over 8 yearsSuggestion: define lambdas that returns that colored string, instead of printing them directly, so that it can be used in conjunction with other strings.
-
Alexander Simko over 8 yearsJust noting: in windows 10, there is no need to enable ansi.sys because the terminal recognizes escape characters.
-
Toby Speight over 8 yearsDon't just throw out terminal codes without checking the value of
$TERM
! Better, use a standard termcap library to refer to them by name... -
Samie Bencherif about 8 yearsTry this snippet to see all the colors and styles your system supports:
print(''.join(['\033[' + str(x) + 'mfoo' for x in range(0,150)]) +'\033[0m')
-
Eryk Sun almost 8 years@AlexanderSimko, I'm not sure what you mean by ansi.sys. That was an MS-DOS driver. Maybe you're referring to ANSICON, which hooks and hacks the Windows console API. The Windows 10 console does natively supports VT100 emulation, but it has to be enabled. If you start Python via cmd.exe it's enabled, but this isn't the default for new consoles, such as running py.exe or python.exe by clicking on a script.
-
Eryk Sun almost 8 years@AlexanderSimko, here's a ctypes code snippet to enable VT100 support in Windows 10:
import ctypes;
kernel32 = ctypes.WinDLL('kernel32');
hStdOut = kernel32.GetStdHandle(-11);
mode = ctypes.c_ulong();
kernel32.GetConsoleMode(hStdOut, ctypes.byref(mode));
mode.value |= 4;
kernel32.SetConsoleMode(hStdOut, mode)
. -
FlipTack over 7 yearscan I ask, which terminal is this?
-
Ruggero Turra over 7 yearshow portable is it?
-
gvalkov over 7 yearsColorama is great! Also have a look at ansimarkup, which is built on colorama and allows you to use a simple tag-based markup (e.g.
<b>bold</b>
) for adding style to terminal text -
Jonathan H over 7 yearsShort standalone implementation: gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920
-
Jamie Counsell over 7 yearsThis is really nice for doing it without a third party package.
-
Zypps987 about 7 yearsWhat shell or terminal makes it blink?
-
qubodup about 7 years(u)rxvt for example
-
balu over 6 years@newbiez There is no difference, both give the same character
ESC
(i.e. the character #27 in the ASCII table).33
and1B
are simply the octal and the hexadecimal representation of the decimal number 27. -
balu over 6 yearsTo anyone using the Python example code from the answer: It should be noted that the colors in the range 90-97 and 100-107 are non-standard and, indeed, on my terminal they don't all give the colors indicated by the variable names. It's better to use the standard ranges 30-37 and 40-47. Source: en.wikipedia.org/wiki/…
-
Martijn Pieters over 6 yearsPython has no
\e
escape sequence. Just because someecho
implementations support it doesn't make those sequences universally available. -
Martijn Pieters over 6 yearsAnd
\e
is not part of the POSIX specification forecho
, so it is not universal there either. The GNU coreutils version supports it, but not the one used on OS X (a BSD variant). Last but not least, the sequence is not a shell feature either, it is specific to theecho
command. -
rnso over 6 yearsPlease see this question stackoverflow.com/questions/47121421/… which has led to these comments.
-
MohitC over 6 yearswhat is the meaning of reset here?
-
Joren over 6 yearsSo when I run a python script with
print('\033[94mfoo')
in my terminal, all the text in my terminal after that is blue... How do I prevent that? -
Noel over 6 years@Joren You need the end the cursor with
\033[0m
. With the example above, appendingbcolors.ENDC
after a previously initiated color. -
pretzlstyle over 6 years
Colorama
comes with Anaconda, whereastermcolor
, suggested in an answer above, does not. This makedColorama
highly preferable for many Python users. -
Smit Johnth over 6 yearsThis doesn't work without calling colorama.init(). Vote up!
-
Romain Vincent over 6 yearsThis will crash if you pass more than one positional argument or anything other than a string type
-
Michael Leonard about 6 years@SmitJohnth only on Windows.
-
Smit Johnth about 6 years@MichaelLeonard this answer shoud be crossplatform, right?
-
Leogout about 6 yearsIf you use the Pycharm console, calling init() on Windows will instead deactivate the colors as it already interprets the ANSI codes and ignores the win32 ones.
-
Michael Leonard about 6 years@SmitJohnth, yes that would make the answer cross platform, which is unarguably good. But saying the code doesn't work without calling init() also isn't right, it works just fine on Unixy systems without it.
-
gcharbon about 6 years@SmitJohnth thanks for the additional info I was struggling to make it work on windows ! This is definetely useful and could be included in the answer.
-
Victor Gavro almost 6 yearsIt would be very useful if you consider to compare it with colorama, I prefer your library, but just because more short api from the box, and it would be great if it will be more popular. Thanks!
-
Giacomo Lacava almost 6 yearsFirst link has gone so I removed it; the GH link is still good (although the project is "archived" and basically abandoned, from what I can gather).
-
ivanleoncz over 5 yearsHey Samat! Would it be nice to mention that you can still use
.format()
for adding variables to the printed string, like this:print(colored('{0}', 'red').format(var_with_msg))
. Nice solution! Tks -
Szabolcs over 5 yearsOn Windows run
os.system('color')
first, then the ANSI escape sequences start working. -
user2023861 over 5 yearsIf you want different colors on the same line, flush the stdout stream in between calls:
print("%X --> %s" % (color, "Have a fine day!"), end='', flush=True)
-
wizzwizz4 over 5 years@Szabolcs You should find that you don't need that on the Windows 10 new terminal, which supports them natively.
-
wizzwizz4 over 5 years@RomainVincent Then don't pass more than one positional argument or anything other than a string ty— wait, these are
print
-replacements? Objection rescinded. -
wizzwizz4 over 5 years@cat That's not necessary;
@contextlib.contextmanager
is a shorthand for making it easier to produce context managers, but you can still use normal context managers. -
Romain Vincent over 5 years@wizzwizz4 I'm not sure what you meant with this comment, I don't see the point anyway. If you are going to propose a class..., to replace a method as simple as print, you might as well avoid making it so easily breakable. Just my opinion.
-
wizzwizz4 over 5 years@RomainVincent I was going to say that your objection was wrong, but for replacing a function as versatile as
print
one should make sure to properly replicate its functionality. -
mazunki over 5 yearsDoes Colorama work for JSON dumps, @JonathanHartley?
-
Jonathan Hartley over 5 years@mazunki The main purpose of Colorama is to allow existing ANSI color codes in a stream to work on Windows. Or, it also allows the author of a Python program to explicitly add their own color codes into things they print (but really, use blessings for that instead.) Colorama does not automatically 'colorize' things like JSON dumps. Use something like `pygmentize' (from Pygments) for that.
-
mazunki over 5 yearsHow do you suggest to mix both of them together?
-
Adversus about 5 yearsNote that importing blessings does not work on windows so don't use it if your script needs to be cross-platform.
-
Jonathan Hartley about 5 yearsI bet you can can use 'pygments' to add colors to some json from within a python program. Then, in the same program,
import colorama
and callcolorama.init()
so that when you print the result to stdout, it works on Windows as well as elsewhere. -
Stuart Axon about 5 yearsThis works - I'm really surprised that the color command enables ANSI codes in the Windows terminal, I've gone for years without knowing this was possible - the command itself doesn't give any clue that it does this.
-
intijk about 5 yearsI like sty and I am trying to format my string with sty, one issue is that , when I print multiple colors, can I reset to previous color instead of default color?
-
Rotareti about 5 years@VictorGavro That's a good idea! I may add a comparison to the documentation.
-
Rotareti about 5 years@intijk Your question doesn't really fit the comment section. For this kind of question please create a new SO Question or use the github issue tracker.
-
gjois almost 5 yearsadding
1;
will also make it bold. Like\033[1;Xm
(where X is color code) -
Danilo almost 5 yearsHonestly this is only solution that works with windows. All other answers are just copy of eachothers.
-
ScipioAfricanus over 4 yearsIs this for python3 only? got an error on sep='' with python2
-
Emilien Baudet over 4 years@RomainVincent Implements to use infinite arguments : <code>
def purple(cls, *args, **kwargs): print(cls.PURPLE, *args, cls.END, **kwargs)
</code> -
Endre Both over 4 yearsFWIW, on Windows it might be less pain to use ConEmu which supports ANSI sequences (apart from a host of other advantages over the native terminal). Still great to have a native solution though.
-
SimpleBinary over 4 years@anaksunaman This will work on all Operating Systems that support coloured text already, as well as supporting Windows 10.
-
SimpleBinary over 4 years@MaxDoesStuff Really? Which Python version are you using? Also which version of MacOS?
-
SimpleBinary over 4 years@Nikos Sorry, I forgot to say that it only works on Windows 10.
-
J-L over 4 yearsThanks so much for your answer, @SimpleBinary! Playing around with your answer, I've found that you can simplify
if sys.platform.lower() == "win32": os.system('color')
even further by simply replacing it with justos.system('')
. No condition is needed, and the code runs in both Windows 10 and Linux (when I tested it). As you can see, you don't have to make a system call tocolor
. Calls todir
,cd
,abcdef
, and just an empty string work fine (although the non-empty strings will likely print output you don't want to see). -
J-L over 4 yearsIn short, the call to
color
isn't the crucial part; it's theos.system(command)
line itself that makes printing colors possible when running on Windows 10. And the "command" can be anything, really -- even just an empty string. -
Sorry IwontTell about 4 yearsI am with Danilo.
-
ncopiy about 4 yearswhen it will be possibility to install it with pip usage?
-
BeastCoder about 4 years@ncopiy Hello! I am actually planning to do that within the next two days! :D For now, you can install it with the install instructions on the page.
-
Ekrem Dinçel about 4 years@Danilo notice this answer: stackoverflow.com/a/3332860/12291742
-
Nathan Chappell almost 4 years@gvalkov thanks for the tip, love your little library. One liner highlighting is clear and concise:
ansiprint(f'<bg white><blue>{h}</blue></bg white>'.join(s.split(h)))
-
BeastCoder almost 4 years@ncopiy It is now available to be installed with
pip3
(orpip
). The command ispip3 install color-it
orpip install color-it
and can be imported withimport colorit
. -
Shane Smiskol almost 4 yearsThe formatting is so nice and it has a lot of color range. I keep coming back to this, thanks!
-
wjandrea almost 4 years@Flip This will work in any terminal/console that supports ANSI escape sequences.
-
Jay almost 4 yearsvery nice, could you please give me some explanation about
"\33[38;5;"
. -
Andriy Makukha almost 4 years@Jay, this is an escape sequence.
'\33'
is the escape character (in octal). -
MACE almost 4 yearsThanks @gustafbstron. This is what I decided to use:
def prGreen: return '"\033[91m {}\033[00m" .format(prt)
which is used like this:print(f'This will turn {prGreen("Hello world")} and change back')
-
vfxdev almost 4 yearsThis should be the accepted answer for python3. Works perfectly.
-
Victor almost 4 yearsI don't know why, but my texts are not colorized by the color provided on the Colors.etc... All my texts are turning into gray texts, but with different tone (lighter / darker)...
-
Victor almost 4 yearsPerfect, this worked for me! The
color-it
solution didn't work for me because my texts were not colorized by the color provided on the Colors.etc... All my texts were turning into gray texts, but with different tone (lighter / darker) -
BeastCoder almost 4 years@Victor Hmm, assuming you have an
init_colorit()
statement somewhere, it may be your terminal. What does it do in other terminals? -
BeastCoder almost 4 years@Victor The other might ne that whatever terminal you are using doesn't support RGB colors, in that case I can work on adding a solution.
-
BeastCoder almost 4 years@Victor Alright, if you are still interested, I fixed the problem, it had to do with how I was initializing
colorit
, I ended up reverting back to the way I was doing so and removingcolorama
's init method. -
Victor almost 4 years@BeastCoder It is not working at all => i.imgur.com/qGqMnxs.jpg I experienced the same issue I said before, I'm using the
click
library to be able to colorize my texts with success. -
n1c9 almost 4 yearsExcellent pure python solution.
-
DoomGoober almost 4 yearsTo make this work in Windows 10 Powershell, in you Python import os then do os.system('color'). From then on, ANSI escape sequences will magically work.
-
mousetail over 3 yearsIn windows 10 colors work like linux if you call
os.system('')
at the beginning of your code -
Abdul Haseeb over 3 yearsAs suggested by @SmitJohnth, You have to run this line of code to work the above code snipped, colorama.init()
-
smassey over 3 yearsThis wasn't asked but I'm glad you shared it regardless! I really prefer this to text colors.
-
BayesianMonk over 3 yearsAnd how one would combine BOLD and COLOURED type?
print(f'{bcolors.OKBLUE}{bcolors.BOLD}Test{bcolors.ENDC}')
will display in blue but not in bold. -
Yan King Yin over 3 yearsOn Linux do:
pip install python-termcolor
-
Mike Pennington over 3 yearsA good reference for how term colors work: jafrog.com/2013/11/23/colors-in-terminal.html
-
Starwarswii over 3 yearsthis is really interesting! why does
os.system("")
cause color codes to work? -
SimpleBinary over 3 years@Starwarswii Any system call seems to work. No idea why. If I find out, I'll put it on here.
-
sakiM over 3 yearsIndeed
os.system('color')
work, furthermore evenos.system('')
work well. very strange -
Peter Mortensen over 3 yearsLinux? What distribution, version, and window manager? Ubuntu 20.04 (Focal Fossa)?
-
Mojtaba Hosseini over 3 yearsAnswer updated for more being precise. Thanks to point out @PeterMortensen
-
Peter Mortensen over 3 yearsAn explanation would be in order.
-
Qohelet over 3 yearsI've been trying this solution. What is the purpose of
"31;40m"
and"0m"
? -
Russell Smith over 3 years@Qohelet: did you follow the link to "ANSI escape code"? It explains how ANSI escape sequences work. The first set of numbers tell the terminal to start using a specific foreground and background color, the
0m
tells the terminal to stop using that color. -
Qohelet over 3 years@BryanOakley - I wonder as this is not happening. Python3.7 prints it as regular text.
-
Russell Smith over 3 yearsAre you running it in a terminal window that supports ANSI escape sequences?
-
NegaOverflow over 3 yearskind reminder: code begin with 5 or 6 are blinking. e.g.
5;37;41
or6;37;41
and the last number can be reaching >=48, which is fully white background. -
uliwitness over 3 yearsFYI - What is labeled "beige" above is a light cyan on Apple's Terminal (and also in many other lists of color names for Python). Also, some of the double colors are light/dark versions, and the white variants I would call white and grey ...
-
MRule about 3 years@intijk : use the codes
fg.rs
andbg.rs
to reset the foreground and background colors to default, respectively. -
bluenote10 about 3 years@LtWorf I disagree. (1) Use cases for passing around the color as a value are pretty rare. Typical use cases are just to use a specific color, and auto-complettion has a big practical benefit. (2) In a language that supports functions as first-class entities, having
Fore.GREEN
ort.on_green
is equivalent, i.e., it is still possible to pass around colors. Look at how chalk does it, the best library I've ever used for colors. -
LtWorf about 3 years@bluenote10 it has been 10 years since that comment. Let it go…
-
bluenote10 about 3 years@LtWorf: Apologies if my comment sounded harsh! I just wanted to offer an alternative view, to avoid readers discarding the beautiful
blessings
library prematurely. Cheers ;) -
CervEd about 3 yearsit's an oversimplification that
colorama.init()
is required to work on Windows, in-fact, it may even break color output on Windows. It depends on the terminal/enviroment -
some dev about 3 years@Starwarswii It's not python's implementation, in C running
printf(fmt, ...);
with ASNI codes in windows after callingsystem("");
(include <stdlib.h>
) does prints the color text, I'm still curious why is that? -
CrazyVideoGamer almost 3 yearsOn windows, you can make ansi escape codes work by running the color command in cmd. Just put in
os.system("color")
-
nosbor almost 3 yearsThis is actually the proper answer to the question and should be selected. The question is how to print colours in python and NOT what external libraries can be used.
-
Roland Pihlakas almost 3 years@captain
\33[25m
should also mean "Not blinking", without resetting other styles - en.wikipedia.org/wiki/… -
starriet almost 3 yearsCompact but informative. Should be upvoted more. Quick question: There seems to be different kinds of "escape" stuff, such as ^[, \033, \u001b, \x1b (you used x1b I guess). What are the differences between them? I tried to search but not very clear.
-
Carl Walsh almost 3 years
termcolor
module's last release was in Jan 2011. -
MatsK over 2 yearsJust some housekeeping, I would have changed the print to
print(style.YELLOW + "Hello, World!" + style.RESET)
-
Benyamin Jafari - aGn over 2 yearsNote that, in python3.x you should add an extra parenthesis after print:
print(colorize(...))
-
schneiderfelipe over 2 yearsThis will always fail if the screen is not large enough (
_curses.error: addwstr() returned ERR
) since it will attempt to write outside the screen... (see here) -
mike rodent over 2 yearsThis printed "←[38;2;255;0;0mbubble ←[38;2;255;255;255m" when I created a red string "bubble". This is a W10 machine... is your solution *nix-specific?
-
alper over 2 yearshow can I make them bold?
-
rbaleksandar over 2 yearsOne thing to note that is important imho is that the code posted in this answer (as also stated by its author) is part of the Blender codebase. As such it is susceptible to Blender's license, which is GPL. I think the code should be changed in a way that it is not longer a problem or write own version of it.
-
not2qubit over 2 yearsThe most likely reason why
os.system("")
makes this work, is that it somehow enables the (Windows10)Virtual Terminal
(VT) settings and UTF-8 (without BOM), when opening a pipe or console handle. Perhaps this answer is correct. You may want to experiment with settingENABLE_VIRTUAL_TERMINAL_PROCESSING
using methods from here. -
UltraStudioLTD over 2 years@mike_rodent This isn't *nix specific but depends on whether terminal supports ANSI
-
alexzander over 2 yearseveryone keep in mind that these colors are
terminal independent
, meaning that if you want some type of green that is not from your terminal'sTERM 256 colors
itsgoing to work
-
Vinod Srivastav over 2 yearsIn case if you are looking for a solution for windows 10, have as look here => stackoverflow.com/a/70599663/3057246
-
P i over 2 yearsThis can be further tidied using a lambda and f-strings: `coloured = lambda r, g, b, text: f'\033[38;2;{r};{g};{b}m{text} \033[38;2;255;255;255m'
-
Qiulang over 2 yearsBut you seem to miss colorful, github.com/timofurrer/colorful
-
Glen Thompson over 2 years@rabin-utam Would be nice if there was a link to these vs just screenshots
-
Elyasaf755 over 2 yearsThere is a side effect trailing space after the current implementation. You can get rid of by removing the trailing space from the string format. Use this instead: f"\033[38;2;{r};{g};{b}m{text}\033[38;2;255;255;255m"
-
CircuitSacul over 2 years@Elyasaf755 thanks, fixed it.
-
Cagy79 over 2 yearsDoesn't seem to work in Powershell: ←[31mOFFLINE←[0m
-
mousetail about 2 years@DoomGoober Running
os.system('')
will also work, IDK why -
Mehdi about 2 yearsInvalid syntax for Python2
-
CircuitSacul about 2 years@Mehdi this wasn't written for python2. Almost everyone is using python3 now, and maintaining backwards compatibility isn't worth the time. If you want it to work for python2, you'll need to use .format() instead of f-strings. Hardly deserves a downvote for not working for an unsupported version of python.
-
hekimgil about 2 yearsYou say "you can use [...]" but I don't see an explanation on how to do it? Am I missing something? Any links, libraries, code, etc. explaining how to do what you mention?
-
Mojtaba Hosseini about 2 yearsDo you mean using emojis ? @hekimgil I have added the instruction of that
-
hekimgil about 2 yearsYes. Is there a special library to put emojis or what? I don't get it? Oh, okay, now you added the emoji picker at the end of the post, thank you... How does that work though? Are the emojis posted as non-ASCII characters or are they a combination of ASCII characters that are interpreted by the displays? More information would be appreciated.
-
Mojtaba Hosseini about 2 yearsEmojis are unicodes. you can find out more about them online by searching "emoji" 😉
-
Fisher about 2 yearsWhen terminal background color is white, exit color will cause problem. Also the exit color is hard coded, even for blackground, it will overtake user specified font color. Better change it to: return f"\033[38;2;{r};{g};{b}m{text}\033[0m".
-
Yaroslav Nikitenko about 2 yearsThere are maybe more powerful color libraries, but this one also provides test scrolling and CL arguments autocomplete, which is perfect!