How do I print colored text to the terminal?

1,923,692

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

Example Screenshot: example screenshot

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

Success with green background example

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)

Enter image description here

Dark-on-light example (partial)

Top part of output

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:

Output colors

Through experimentation, we can get more colors:

Color matrix

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
Share:
1,923,692
aboSamoor
Author by

aboSamoor

Updated on May 04, 2022

Comments

  • aboSamoor
    aboSamoor about 2 years

    How can I output colored text to the terminal in Python?

    • Samie Bencherif
      Samie Bencherif over 10 years
      This symbol would make a great colored block: Only problem is that it is extended ASCII, maybe you could get it to work using http://stackoverflow.com/questions/8465226/using-extended-as‌​cii-codes-with-pytho‌​n
    • ayke
      ayke over 10 years
      Some terminals also can display Unicode characters. If that is true for your terminal, the possible characters are almost unlimited.
    • ArtOfWarfare
      ArtOfWarfare over 10 years
      This 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
      alvas over 7 years
      How about stackoverflow.com/a/42528796/610569 using pypi.python.org/pypi/lazyme ? (disclaimer: shameless plug)
    • Benyamin Jafari - aGn
      Benyamin Jafari - aGn over 3 years
      If you don't want to install an extra package, follow this new answer.
  • nosklo
    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
    Jonathan Hartley almost 14 years
    As 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
    Phil P almost 13 years
    Since it's emitting ANSI codes, does it work on Windows (DOS consoles) if ansi.sys is loaded? support.microsoft.com/kb/101875
  • Alexander Tsepkov
    Alexander Tsepkov over 12 years
    Just noticed that as of 13/01/2011, it's now under MIT license
  • Adobe
    Adobe almost 12 years
    But suppose my default prompt is not black - do You think it's possible to make python resotre after these tricks?
  • Dennis
    Dennis over 11 years
    Another useful one is UNDERLINE = '\033[4m'. What happens if ansi.sys is disabled on Windows and you try to use these ANSI escape sequences?
  • Martin Ueding
    Martin Ueding over 11 years
    On Linux, you might want to use tput, like so since it results in more portable code.
  • Demolishun
    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
    LtWorf over 11 years
    Putting the color as a function name and not as a parameter is a questionable practice.
  • pragmatic
    pragmatic over 11 years
    More on this can be found here- linux.byexamples.com/archives/184/…
  • daviewales
    daviewales about 11 years
    This should be in the standard library... Cross platform colour support is important, I think.
  • Janus Troelsen
    Janus Troelsen almost 11 years
    doesn't have unittests (unlike colorama) and not updated since 2011
  • Tom
    Tom over 10 years
    Tried out colorama, used print(Style.BRIGHT + "Header Test") and print (Style.DIM + word) to create a really nice prompt.
  • Evgeni Sergeev
    Evgeni Sergeev over 10 years
    Try def d(*v): return '\x1B['+';'.join(map(str, v))+'m' then print ' '.join([d(k,i)+str(i%10)+d(0) for i in range(30,38)+range(40,48) for k in range(2)])
  • dashesy
    dashesy over 10 years
    this works in most shells as well as ipython, good enough for most applications
  • Sebastian Mach
    Sebastian Mach about 10 years
    @Cawas: A real use case for disable is when you pipe the output to a file; while tools like cat may support colors, it is generally better to not print color information to files.
  • cregox
    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
    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
    Ethan Bierlein about 10 years
    @joeld is it possible to do variants of one color?
  • ereOn
    ereOn over 9 years
    There 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
    Floyd about 9 years
    Not very nice code, it even contains a reference to pythonw.exe ;)
  • dtk
    dtk about 9 years
  • Admin
    Admin almost 9 years
    What is the difference between the \033[ and the \x1b[ ? They seem to do the same thing
  • mike
    mike almost 9 years
    Just noting: The Python Curses module is also available in Python 3 docs.python.org/3/howto/curses.html
  • Jonathan Hartley
    Jonathan Hartley almost 9 years
    Personally I think that the 'curses' library has been totally eclipsed by 'blessings', in the same way 'requests' has eclipsed 'urllib', etc.
  • mike3996
    mike3996 over 8 years
    @LtWorf: why? Python's functions and methods are first-class citizens
  • LtWorf
    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
    akxlr over 8 years
    termcolor.COLORS gives you a list of colours
  • MaxNoe
    MaxNoe over 8 years
    You can just pass a python function.
  • cat
    cat over 8 years
    This will need to change to use contextlib for Py3.
  • Janus Troelsen
    Janus Troelsen over 8 years
    @cat: From what version of Python will that be necessary?
  • cat
    cat over 8 years
    I believe 3 and up -- it should have a @contextlib.contextmanager decorator on it, no?
  • Janus Troelsen
    Janus Troelsen over 8 years
    @cat: Why? Works great without.
  • gustafbstrom
    gustafbstrom over 8 years
    Suggestion: 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
    Alexander Simko over 8 years
    Just noting: in windows 10, there is no need to enable ansi.sys because the terminal recognizes escape characters.
  • Toby Speight
    Toby Speight over 8 years
    Don'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
    Samie Bencherif about 8 years
    Try 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
    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
    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
    FlipTack over 7 years
    can I ask, which terminal is this?
  • Ruggero Turra
    Ruggero Turra over 7 years
    how portable is it?
  • gvalkov
    gvalkov over 7 years
    Colorama 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
    Jonathan H over 7 years
  • Jamie Counsell
    Jamie Counsell over 7 years
    This is really nice for doing it without a third party package.
  • Zypps987
    Zypps987 about 7 years
    What shell or terminal makes it blink?
  • qubodup
    qubodup about 7 years
    (u)rxvt for example
  • balu
    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 and 1B are simply the octal and the hexadecimal representation of the decimal number 27.
  • balu
    balu over 6 years
    To 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
    Martijn Pieters over 6 years
    Python has no \e escape sequence. Just because some echo implementations support it doesn't make those sequences universally available.
  • Martijn Pieters
    Martijn Pieters over 6 years
    And \e is not part of the POSIX specification for echo, 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 the echo command.
  • rnso
    rnso over 6 years
    Please see this question stackoverflow.com/questions/47121421/… which has led to these comments.
  • MohitC
    MohitC over 6 years
    what is the meaning of reset here?
  • Joren
    Joren over 6 years
    So 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
    Noel over 6 years
    @Joren You need the end the cursor with \033[0m. With the example above, appending bcolors.ENDC after a previously initiated color.
  • pretzlstyle
    pretzlstyle over 6 years
    Colorama comes with Anaconda, whereas termcolor, suggested in an answer above, does not. This maked Colorama highly preferable for many Python users.
  • Smit Johnth
    Smit Johnth over 6 years
    This doesn't work without calling colorama.init(). Vote up!
  • Romain Vincent
    Romain Vincent over 6 years
    This will crash if you pass more than one positional argument or anything other than a string type
  • Michael Leonard
    Michael Leonard about 6 years
    @SmitJohnth only on Windows.
  • Smit Johnth
    Smit Johnth about 6 years
    @MichaelLeonard this answer shoud be crossplatform, right?
  • Leogout
    Leogout about 6 years
    If 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
    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
    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
    Victor Gavro almost 6 years
    It 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
    Giacomo Lacava almost 6 years
    First 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
    ivanleoncz over 5 years
    Hey 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
    Szabolcs over 5 years
    On Windows run os.system('color') first, then the ANSI escape sequences start working.
  • user2023861
    user2023861 over 5 years
    If 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
    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
    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
    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
    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
    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
    mazunki over 5 years
    Does Colorama work for JSON dumps, @JonathanHartley?
  • Jonathan Hartley
    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
    mazunki over 5 years
    How do you suggest to mix both of them together?
  • Adversus
    Adversus about 5 years
    Note that importing blessings does not work on windows so don't use it if your script needs to be cross-platform.
  • Jonathan Hartley
    Jonathan Hartley about 5 years
    I 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 call colorama.init() so that when you print the result to stdout, it works on Windows as well as elsewhere.
  • Stuart Axon
    Stuart Axon about 5 years
    This 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
    intijk about 5 years
    I 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
    Rotareti about 5 years
    @VictorGavro That's a good idea! I may add a comparison to the documentation.
  • Rotareti
    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
    gjois almost 5 years
    adding 1; will also make it bold. Like \033[1;Xm (where X is color code)
  • Danilo
    Danilo almost 5 years
    Honestly this is only solution that works with windows. All other answers are just copy of eachothers.
  • ScipioAfricanus
    ScipioAfricanus over 4 years
    Is this for python3 only? got an error on sep='' with python2
  • Emilien Baudet
    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
    Endre Both over 4 years
    FWIW, 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
    SimpleBinary over 4 years
    @anaksunaman This will work on all Operating Systems that support coloured text already, as well as supporting Windows 10.
  • SimpleBinary
    SimpleBinary over 4 years
    @MaxDoesStuff Really? Which Python version are you using? Also which version of MacOS?
  • SimpleBinary
    SimpleBinary over 4 years
    @Nikos Sorry, I forgot to say that it only works on Windows 10.
  • J-L
    J-L over 4 years
    Thanks 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 just os.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 to color. Calls to dir, 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
    J-L over 4 years
    In short, the call to color isn't the crucial part; it's the os.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
    Sorry IwontTell about 4 years
    I am with Danilo.
  • ncopiy
    ncopiy about 4 years
    when it will be possibility to install it with pip usage?
  • BeastCoder
    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
    Ekrem Dinçel about 4 years
    @Danilo notice this answer: stackoverflow.com/a/3332860/12291742
  • Nathan Chappell
    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
    BeastCoder almost 4 years
    @ncopiy It is now available to be installed with pip3 (or pip). The command is pip3 install color-it or pip install color-it and can be imported with import colorit.
  • Shane Smiskol
    Shane Smiskol almost 4 years
    The formatting is so nice and it has a lot of color range. I keep coming back to this, thanks!
  • wjandrea
    wjandrea almost 4 years
    @Flip This will work in any terminal/console that supports ANSI escape sequences.
  • Jay
    Jay almost 4 years
    very nice, could you please give me some explanation about "\33[38;5;" .
  • Andriy Makukha
    Andriy Makukha almost 4 years
    @Jay, this is an escape sequence. '\33' is the escape character (in octal).
  • MACE
    MACE almost 4 years
    Thanks @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
    vfxdev almost 4 years
    This should be the accepted answer for python3. Works perfectly.
  • Victor
    Victor almost 4 years
    I 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
    Victor almost 4 years
    Perfect, 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
    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
    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
    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 removing colorama's init method.
  • Victor
    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
    n1c9 almost 4 years
    Excellent pure python solution.
  • DoomGoober
    DoomGoober almost 4 years
    To 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
    mousetail over 3 years
    In windows 10 colors work like linux if you call os.system('') at the beginning of your code
  • Abdul Haseeb
    Abdul Haseeb over 3 years
    As suggested by @SmitJohnth, You have to run this line of code to work the above code snipped, colorama.init()
  • smassey
    smassey over 3 years
    This wasn't asked but I'm glad you shared it regardless! I really prefer this to text colors.
  • BayesianMonk
    BayesianMonk over 3 years
    And 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
    Yan King Yin over 3 years
    On Linux do: pip install python-termcolor
  • Mike Pennington
    Mike Pennington over 3 years
  • Starwarswii
    Starwarswii over 3 years
    this is really interesting! why does os.system("") cause color codes to work?
  • SimpleBinary
    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
    sakiM over 3 years
    Indeed os.system('color') work, furthermore even os.system('') work well. very strange
  • Peter Mortensen
    Peter Mortensen over 3 years
    Linux? What distribution, version, and window manager? Ubuntu 20.04 (Focal Fossa)?
  • Mojtaba Hosseini
    Mojtaba Hosseini over 3 years
    Answer updated for more being precise. Thanks to point out @PeterMortensen
  • Peter Mortensen
    Peter Mortensen over 3 years
    An explanation would be in order.
  • Qohelet
    Qohelet over 3 years
    I've been trying this solution. What is the purpose of "31;40m" and "0m"?
  • Russell Smith
    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
    Qohelet over 3 years
    @BryanOakley - I wonder as this is not happening. Python3.7 prints it as regular text.
  • Russell Smith
    Russell Smith over 3 years
    Are you running it in a terminal window that supports ANSI escape sequences?
  • NegaOverflow
    NegaOverflow over 3 years
    kind reminder: code begin with 5 or 6 are blinking. e.g. 5;37;41 or 6;37;41 and the last number can be reaching >=48, which is fully white background.
  • uliwitness
    uliwitness over 3 years
    FYI - 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
    MRule about 3 years
    @intijk : use the codes fg.rs and bg.rs to reset the foreground and background colors to default, respectively.
  • bluenote10
    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 or t.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
    LtWorf about 3 years
    @bluenote10 it has been 10 years since that comment. Let it go…
  • bluenote10
    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
    CervEd about 3 years
    it'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
    some dev about 3 years
    @Starwarswii It's not python's implementation, in C running printf(fmt, ...); with ASNI codes in windows after calling system(""); (include <stdlib.h>) does prints the color text, I'm still curious why is that?
  • CrazyVideoGamer
    CrazyVideoGamer almost 3 years
    On windows, you can make ansi escape codes work by running the color command in cmd. Just put in os.system("color")
  • nosbor
    nosbor almost 3 years
    This 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
    Roland Pihlakas almost 3 years
    @captain \33[25m should also mean "Not blinking", without resetting other styles - en.wikipedia.org/wiki/…
  • starriet
    starriet almost 3 years
    Compact 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
    Carl Walsh almost 3 years
    termcolor module's last release was in Jan 2011.
  • MatsK
    MatsK over 2 years
    Just some housekeeping, I would have changed the print to print(style.YELLOW + "Hello, World!" + style.RESET)
  • Benyamin Jafari - aGn
    Benyamin Jafari - aGn over 2 years
    Note that, in python3.x you should add an extra parenthesis after print: print(colorize(...))
  • schneiderfelipe
    schneiderfelipe over 2 years
    This 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
    mike rodent over 2 years
    This 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
    alper over 2 years
    how can I make them bold?
  • rbaleksandar
    rbaleksandar over 2 years
    One 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
    not2qubit over 2 years
    The 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 setting ENABLE_VIRTUAL_TERMINAL_PROCESSING using methods from here.
  • UltraStudioLTD
    UltraStudioLTD over 2 years
    @mike_rodent This isn't *nix specific but depends on whether terminal supports ANSI
  • alexzander
    alexzander over 2 years
    everyone keep in mind that these colors are terminal independent, meaning that if you want some type of green that is not from your terminal's TERM 256 colors its going to work
  • Vinod Srivastav
    Vinod Srivastav over 2 years
    In case if you are looking for a solution for windows 10, have as look here => stackoverflow.com/a/70599663/3057246
  • P i
    P i over 2 years
    This 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
    Qiulang over 2 years
    But you seem to miss colorful, github.com/timofurrer/colorful
  • Glen Thompson
    Glen Thompson over 2 years
    @rabin-utam Would be nice if there was a link to these vs just screenshots
  • Elyasaf755
    Elyasaf755 over 2 years
    There 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
    CircuitSacul over 2 years
    @Elyasaf755 thanks, fixed it.
  • Cagy79
    Cagy79 over 2 years
    Doesn't seem to work in Powershell: ←[31mOFFLINE←[0m
  • mousetail
    mousetail about 2 years
    @DoomGoober Running os.system('') will also work, IDK why
  • Mehdi
    Mehdi about 2 years
    Invalid syntax for Python2
  • CircuitSacul
    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
    hekimgil about 2 years
    You 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
    Mojtaba Hosseini about 2 years
    Do you mean using emojis ? @hekimgil I have added the instruction of that
  • hekimgil
    hekimgil about 2 years
    Yes. 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
    Mojtaba Hosseini about 2 years
    Emojis are unicodes. you can find out more about them online by searching "emoji" 😉
  • Fisher
    Fisher about 2 years
    When 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
    Yaroslav Nikitenko about 2 years
    There are maybe more powerful color libraries, but this one also provides test scrolling and CL arguments autocomplete, which is perfect!