Colors in Python not showing [duplicate] - python

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

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.

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

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 init as colorama_init
from colorama import Fore
from colorama import Style
colorama_init()
print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")
Example Screenshot:

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

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

Here's a solution that works on Windows 10 natively.
Using a system call, such as os.system(""), allows colours to be printed in Command Prompt and Powershell natively:
import os
# System call
os.system("")
# Class of different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
print(style.YELLOW + "Hello, World!")
Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.
Thanks to #j-l for finding an even shorter method.
tl;dr: Add os.system("")

You want to learn about ANSI escape sequences. Here's a brief example:
CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
For more information, see ANSI escape code.
For a block character, try a Unicode character like \u2588:
print(u"\u2588")
Putting it all together:
print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

sty is similar to colorama, but it's less verbose, supports 8-bit and 24-bit (RGB) colors, supports all effects (bold, underline, etc.), allows you to register your own styles, is fully typed and high performant, supports muting, is not messing with globals such as sys.stdout, is really flexible, well documented and more...
Examples:
from sty import fg, bg, ef, rs
foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
# Add custom colors:
from sty import Style, RgbFg
fg.orange = Style(RgbFg(255, 150, 50))
buf = fg.orange + 'Yay, Im orange.' + fg.rs
print(foo, bar, baz, qux, qui, buf, sep='\n')
prints:
Demo:

Rich is a relatively new Python library for working with color in the terminal.
There are a few ways of working with color in Rich. The quickest way to get started would be the rich print method which renders a BBCode-like syntax in to ANSI control codes:
from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")
There are other ways of applying color with Rich (regex, syntax) and related formatting features.

My favorite way is with the Blessings library (full disclosure: I wrote it). For example:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:
print t.on_green(' ')
You can print in specific locations as well:
with t.location(0, 5):
print t.on_yellow(' ')
If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:
print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!

I generated a class with all the colors using a for loop to iterate every combination of color up to 100, and then wrote a class with Python colors. Copy and paste as you will, GPLv2 by me:
class colors:
'''Colors class:
Reset all colors with colors.reset
Two subclasses fg for foreground and bg for background.
Use as colors.subclass.colorname.
i.e. colors.fg.red or colors.bg.green
Also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. colors.bold
'''
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class fg:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class bg:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'

This is, in my opinion, the easiest method. As long as you have the RGB values of the color you want, this should work:
def colored(r, g, b, text):
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
An example of printing red text:
text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)
#or
print(colored(255, 0, 0, 'Hello, World!'))
Multi-colored text
text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)

Try this simple code
def prRed(prt):
print(f"\033[91m{prt}\033[00m")
def prGreen(prt):
print(f"\033[92m{prt}\033[00m")
def prYellow(prt):
print(f"\033[93m{prt}\033[00m")
def prLightPurple(prt):
print(f"\033[94m{prt}\033[00m")
def prPurple(prt):
print(f"\033[95m{prt}\033[00m")
def prCyan(prt):
print(f"\033[96m{prt}\033[00m")
def prLightGray(prt):
print(f"\033[97m{prt}\033[00m")
def prBlack(prt):
print(f"\033[98m{prt}\033[00m")
def prReset(prt):
print(f"\033[0m{prt}\033[00m")
prGreen("Hello, Green World!")
prBlack("Hello, Black World!")
prCyan("Hello, Cyan World!")
prGreen("Hello, Green World!")
prLightGray("Hello, Light Grey World!")
prLightPurple("Hello, Light Purple World!")
prPurple("Hello, Purple World!")
prRed("Hello, Red World!")
prYellow("Hello, Yellow World!")
prReset("Hello, Reset World!")
Python 3 Example
# python2
def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))
prGreen("Hello, World!")

# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS
fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def print_six(row, format, end="\n"):
for col in range(6):
color = row*6 + col - 2
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(end=" ") # four spaces
print(end=end)
for row in range(0, 43):
print_six(row, fg, " ")
print_six(row, bg)
# Simple usage: print(fg("text", 160))
Try it online

I have a library called colorit. It is super simple.
Here are some examples:
from colorit import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()
# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))
# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))
# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))
# Combination
print(
background(
color("This text is blue with a white background", Colors.blue), Colors.white
)
)
# If you are using Windows Command Line, this is so that it doesn't close immediately
input()
This gives you:
It's also worth noting that this is cross platform and has been tested on Mac, Linux, and Windows.
You might want to try it out: https://github.com/SuperMaZingCoder/colorit
colorit is now available to be installed with PyPi! You can install it with pip install color-it on Windows and pip3 install color-it on macOS and Linux.

On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.
To see complete code that supports both ways, see the color console reporting code from Testoob.
ctypes example:
import ctypes
# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED = 0x0004 # text color contains red.
def get_csbi_attributes(handle):
# Based on IPython's winconsole.py, written by Alexander Belchenko
import struct
csbi = ctypes.create_string_buffer(22)
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
assert res
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
return wattr
handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)

I have wrapped joeld's answer into a module with global functions that I can use anywhere in my code.
File: log.py
def enable():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = "\033[1m"
def disable():
HEADER = ''
OKBLUE = ''
OKGREEN = ''
WARNING = ''
FAIL = ''
ENDC = ''
def infog(msg):
print(OKGREEN + msg + ENDC)
def info(msg):
print(OKBLUE + msg + ENDC)
def warn(msg):
print(WARNING + msg + ENDC)
def err(msg):
print(FAIL + msg + ENDC)
enable()
Use as follows:
import log
log.info("Hello, World!")
log.err("System Error")

def black(text):
print('\033[30m', text, '\033[0m', sep='')
def red(text):
print('\033[31m', text, '\033[0m', sep='')
def green(text):
print('\033[32m', text, '\033[0m', sep='')
def yellow(text):
print('\033[33m', text, '\033[0m', sep='')
def blue(text):
print('\033[34m', text, '\033[0m', sep='')
def magenta(text):
print('\033[35m', text, '\033[0m', sep='')
def cyan(text):
print('\033[36m', text, '\033[0m', sep='')
def gray(text):
print('\033[90m', text, '\033[0m', sep='')
black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")
Try online

Here is my modern (2021) solution: yachalk
It is one of the few libraries that properly supports nested styles:
Apart from that yachalk is auto-complete-friendly, has 256/truecolor support, comes with terminal-capability detection, and is fully typed.
Here are some design decision you may consider for choosing your solution.
High-level libraries vs low-level libraries / manual style handling?
Many answers to this question demonstrate how to ANSI escape codes directly, or suggest low-level libraries that require manual style enabling/disabling.
These approaches have subtle issues: Inserting on/off styles manually is
more verbose syntactically, because resets have to be specified explicitly,
more error prone, because you can accidentally forget to reset a style,
fails to get edge cases right: For instance in some terminals it is necessary to reset styles before newlines, and re-activate them after the line break. Also, some terminal have problems with simply overriding mutually exclusive styles, and require inserting "unnecessary" reset codes. If a developer's local terminal doesn't have these quirks, the developer will not discover these quirks immediately. The issue will only be reported later by others or cause problems e.g. on CI terminals.
Therefore if compatibility with many terminals is a goal, it's best to use a high-level library that offers automatic handling of style resets. This allows the library to take care of all edge cases by inserting the "spurious" ANSI escape codes where needed.
Why yet another library?
In JavaScript the de-facto standard library for the task is chalk, and after using it for a while in JS projects, the solutions available in the Python world were lacking in comparison. Not only is the chalk API more convenient to use (fully auto-complete compatible), it also gets all the edge cases right.
The idea of yachalk is to bring the same convenience to the Python ecosystem. If you're interested in a comparison to other libraries I've started feature comparison on the projects page. In addition, here is a long (but still incomplete) list of alternatives that came up during my research -- a lot to choose from :)
colored
ansicolors
termcolor
colorama
sty
blessings
rich
colorit
colorprint
console-color
pyfance
couleur
style (formerly known as clr)
pychalk
simple-chalk
chlk
chalky
constyle

I ended up doing this, and I felt it was cleanest:
formatters = {
'RED': '\033[91m',
'GREEN': '\033[92m',
'END': '\033[0m',
}
print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)

For Windows you cannot print to console with colors unless you're using the Win32 API.
For Linux it's as simple as using print, with the escape sequences outlined here:
Colors
For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:
#

Stupidly simple, based on joeld's answer:
class PrintInColor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
#classmethod
def red(cls, s, **kwargs):
print(cls.RED + s + cls.END, **kwargs)
#classmethod
def green(cls, s, **kwargs):
print(cls.GREEN + s + cls.END, **kwargs)
#classmethod
def yellow(cls, s, **kwargs):
print(cls.YELLOW + s + cls.END, **kwargs)
#classmethod
def lightPurple(cls, s, **kwargs):
print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
#classmethod
def purple(cls, s, **kwargs):
print(cls.PURPLE + s + cls.END, **kwargs)
Then just
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

Building on joeld's answer, using https://pypi.python.org/pypi/lazyme
pip install -U lazyme:
from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc
Screenshot:
Some updates to the color_print with new formatters, e.g.:
>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter,
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
Note: italic, fast blinking, and strikethrough may not work on all terminals, and they don't work on Mac and Ubuntu.
E.g.,
>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar
Screenshot:

Note how well the with keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):
from colorama import Fore, Style
import sys
class Highlight:
def __init__(self, clazz, color):
self.color = color
self.clazz = clazz
def __enter__(self):
print(self.color, end="")
def __exit__(self, type, value, traceback):
if self.clazz == Fore:
print(Fore.RESET, end="")
else:
assert self.clazz == Style
print(Style.RESET_ALL, end="")
sys.stdout.flush()
with Highlight(Fore, Fore.GREEN):
print("this is highlighted")
print("this is not")

You could use Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')

You can use the Python implementation of the curses library:
curses — Terminal handling for character-cell displays
Also, run this and you'll find your box:
for i in range(255):
print i, chr(i)

Emoji
You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color.
But you can use emojis instead! for example, you can use⚠️ for warning messages and 🛑 for error messages.
Or simply use these notebooks as a color:
📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color
🎁 Bonus:
This method also helps you to quickly scan and find logs directly in the source code.
But some operating systems (including some Linux distributions in some version with some window managers) default emoji font is not colorful by default and you may want to make them colorful, first.
How to open emoji picker?
mac os: control + command + space
windows: win + .
linux: control + . or control + ;

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"

An easier option would be to use the cprint function from the termcolor package.
It also supports %s, %d format of printing:
Results can be terminal dependant, so review the Terminal Properties section of the package documentation.
Windows Command Prompt and Python IDLE don't work
JupyterLab notebook does work

YAY! Another version
While I find this answer useful, I modified it a bit. This GitHub Gist is the result
Usage
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
In addition, you can wrap common usages:
print colors.error('sorry, ')
https://gist.github.com/Jossef/0ee20314577925b4027f

Related

When I use the rich library to add colour, why does it affect the symbols around it? Is there a way to stop this from happening?

What am I trying to do?
I am using the rich library to print words out in different colours.
I have come up with the following program to do so:
from rich import print as rprint
rprint('[[green]1[/green]] Create new password')
print('[2] See existing passwords')
print('[3] Exit')
Output:
My Problem
As you can see on the image above, the square brackets which surround 1 are a brighter in color compared to the ones beneath it 2 & 3. Is there a way to make the square brackets all the same color (grey) instead of a white?
Thanks in advance.
Note:
I am aware that this does not hinder how the program works but I like things to be aesthetically pleasing and this is really bugging me for some reason.
Also, I was just testing how I could go about changing colours using rich, but I'm open to suggestions on other ways do this.
Rich performs highlighting on the output, for numbers, strings, data etc. In your example it is highlighting braces, which can be helpful when you print data structures.
You can disable this feature if you construct a Console object and set highlight=False on the print method.
Here's an example:
from rich.console import Console
console = Console()
console.print('[[green]1[/green]] Create new password', highlight=False)
See the docs on highlighting for the details.
As the op is open to other ways, here is my way of doing..
Initiate a class with standard terminal color codes.
class bcolors:
ResetAll = "\033[0m"
Bold = "\033[1m"
Dim = "\033[2m"
Underlined = "\033[4m"
Blink = "\033[5m"
Reverse = "\033[7m"
Hidden = "\033[8m"
ResetBold = "\033[21m"
ResetDim = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink = "\033[25m"
ResetReverse = "\033[27m"
ResetHidden = "\033[28m"
Default = "\033[39m"
Black = "\033[30m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
LightGray = "\033[37m"
DarkGray = "\033[90m"
LightRed = "\033[91m"
LightGreen = "\033[92m"
LightYellow = "\033[93m"
LightBlue = "\033[94m"
LightMagenta = "\033[95m"
LightCyan = "\033[96m"
White = "\033[97m"
BackgroundDefault = "\033[49m"
BackgroundBlack = "\033[40m"
BackgroundRed = "\033[41m"
BackgroundGreen = "\033[42m"
BackgroundYellow = "\033[43m"
BackgroundBlue = "\033[44m"
BackgroundMagenta = "\033[45m"
BackgroundCyan = "\033[46m"
BackgroundLightGray = "\033[47m"
BackgroundDarkGray = "\033[100m"
BackgroundLightRed = "\033[101m"
BackgroundLightGreen = "\033[102m"
BackgroundLightYellow = "\033[103m"
BackgroundLightBlue = "\033[104m"
BackgroundLightMagenta = "\033[105m"
BackgroundLightCyan = "\033[106m"
BackgroundWhite = "\033[107m"
Your Program
print(f"[{bcolors.Green}1{bcolors.ResetAll}] Create new password")
print('[2] See existing passwords')
print('[3] Exit')
Output:

how to make the output prompt from input() be in color (python)?

Apparently the TA in the lab for my AI course wants the codes submitted to be "Highly Readable" and that we should use colors.
anyway been trying to manipulate color in output texts, changing output text for print() is easy, but it's pretty annoying for the input() method.
i tried using libraries like termcolor and colorama but they didn't work.
one method that worked is doing the following:
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
x1 = input(GREEN + "some text in green")
x2 = input(RED + "some text in red")
for some reason the code works in random online compiler sites but not on my python shell or in a ipynb cell like in google collab, anyone has any idea?

Python: How can I make a new line when printing?

I am using Cmd, PIL, and Image to make a program called Visual Object Creator, aka VOC. I made a command prompt and when you type in a command, let's say, bluesquare, it creates just that. But when I do, it makes the image right in front of my command prompt. It looks terribly ugly. It makes me type the command in the next line, away from the (Cmd) prompt. It's hard to explain, just use trinket.io and see my problem, because that's the only compiler I find that works
I tried using /n and printing simply a blank line, but it never worked. I have seen the /n being used but it simply prints the actual /n and not the blank line. I am sorry I pasted the whole file, but every image creating command that I programmed does it!
from PIL import Image
from cmd import Cmd
class Root(Cmd):
intro = "Visual Object Creator v.04."
prompt = ">"
def do_redsquare(self, inp):
print("VOC created this image for you! rsqr.jpg")
rs = Image.new("RGB", (50, 50), color = "red")
rs.save("rsqr.jpg")
def help_redsquare(self):
print("VOC creates a red square under the filename rsqr.jpg.")
def do_exit(self, inp):
return True
def help_exit(self):
print("Ends the VOC application.")
def do_greensquare(self, inp):
print("VOC created this image for you! gsqr.jpg")
gs = Image.new("RGB", (50, 50), color = "green")
gs.save("gsqr.jpg")
def help_greensquare(self):
print("VOC creates a green sqare under the filename gsqr.jpg.")
def do_bluesquare(self, inp):
print("VOC created this image for you! bsqr.jpg")
bs = Image.new("RGB", (50, 50), color = "blue")
bs.save("bsqr.jpg")
def help_bluesquare(self):
print("VOC creates a blue square under the filename bsqr.jpg")
Root().cmdloop()
There were no errors, but it was making me enter commands on a blank line when I actually want to do it on the line of the (cmd) prompt.
The correct newline character for python is \n.
The \ (backslash) is used to start an "escape sequence" which has special
meaning to Python. Some of the options are:
\n newline
\t tab
\\ backslash
print() should print a blank line. Example:
print('line 1')
print()
print('line 2')
will output:
line 1
line 2

How to add colors to printed text?

I am very new to Python/coding in general, and I'm working on a text-based game where two players work together to fight a Boss. It's close to finished, but I'd like to color some of the text.
I looked up my problem, and based on what I found I tried copying and pasting
" print("\033[1;32;40m Bright Green \n") "
and
" print '\033[1;31mRed like Radish\033[1;m' "
but neither worked.
I'm coding this in Atom and running it in IDLE.
There were no syntax errors, it simply printed the \033[1;32;40m along with the text, rather than coloring the text.
You can use good modules like termcolor:
import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red')
print(text)
cprint('Hello, World!', 'green', 'on_red')
print_red_on_cyan = lambda x: cprint(x, 'red', 'on_cyan')
print_red_on_cyan('Hello, World!')
for i in range(10):
cprint(i, 'magenta', end=' ')
cprint("Attention!", 'red', attrs=['bold'], file=sys.stderr)
or colorama:
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

How do I print colored text to the terminal?

How do I output colored text to the terminal in Python?
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.
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')
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 init as colorama_init
from colorama import Fore
from colorama import Style
colorama_init()
print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")
Example Screenshot:
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
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
Here's a solution that works on Windows 10 natively.
Using a system call, such as os.system(""), allows colours to be printed in Command Prompt and Powershell natively:
import os
# System call
os.system("")
# Class of different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
print(style.YELLOW + "Hello, World!")
Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.
Thanks to #j-l for finding an even shorter method.
tl;dr: Add os.system("")
You want to learn about ANSI escape sequences. Here's a brief example:
CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
For more information, see ANSI escape code.
For a block character, try a Unicode character like \u2588:
print(u"\u2588")
Putting it all together:
print(CSI+"31;40m" + u"\u2588" + CSI + "0m")
sty is similar to colorama, but it's less verbose, supports 8-bit and 24-bit (RGB) colors, supports all effects (bold, underline, etc.), allows you to register your own styles, is fully typed and high performant, supports muting, is not messing with globals such as sys.stdout, is really flexible, well documented and more...
Examples:
from sty import fg, bg, ef, rs
foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
# Add custom colors:
from sty import Style, RgbFg
fg.orange = Style(RgbFg(255, 150, 50))
buf = fg.orange + 'Yay, Im orange.' + fg.rs
print(foo, bar, baz, qux, qui, buf, sep='\n')
prints:
Demo:
Rich is a relatively new Python library for working with color in the terminal.
There are a few ways of working with color in Rich. The quickest way to get started would be the rich print method which renders a BBCode-like syntax in to ANSI control codes:
from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")
There are other ways of applying color with Rich (regex, syntax) and related formatting features.
My favorite way is with the Blessings library (full disclosure: I wrote it). For example:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:
print t.on_green(' ')
You can print in specific locations as well:
with t.location(0, 5):
print t.on_yellow(' ')
If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:
print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!
I generated a class with all the colors using a for loop to iterate every combination of color up to 100, and then wrote a class with Python colors. Copy and paste as you will, GPLv2 by me:
class colors:
'''Colors class:
Reset all colors with colors.reset
Two subclasses fg for foreground and bg for background.
Use as colors.subclass.colorname.
i.e. colors.fg.red or colors.bg.green
Also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. colors.bold
'''
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class fg:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class bg:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'
This is, in my opinion, the easiest method. As long as you have the RGB values of the color you want, this should work:
def colored(r, g, b, text):
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
An example of printing red text:
text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)
#or
print(colored(255, 0, 0, 'Hello, World!'))
Multi-colored text
text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)
Try this simple code
def prRed(prt):
print(f"\033[91m{prt}\033[00m")
def prGreen(prt):
print(f"\033[92m{prt}\033[00m")
def prYellow(prt):
print(f"\033[93m{prt}\033[00m")
def prLightPurple(prt):
print(f"\033[94m{prt}\033[00m")
def prPurple(prt):
print(f"\033[95m{prt}\033[00m")
def prCyan(prt):
print(f"\033[96m{prt}\033[00m")
def prLightGray(prt):
print(f"\033[97m{prt}\033[00m")
def prBlack(prt):
print(f"\033[98m{prt}\033[00m")
def prReset(prt):
print(f"\033[0m{prt}\033[00m")
prGreen("Hello, Green World!")
prBlack("Hello, Black World!")
prCyan("Hello, Cyan World!")
prGreen("Hello, Green World!")
prLightGray("Hello, Light Grey World!")
prLightPurple("Hello, Light Purple World!")
prPurple("Hello, Purple World!")
prRed("Hello, Red World!")
prYellow("Hello, Yellow World!")
prReset("Hello, Reset World!")
Python 3 Example
# python2
def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))
prGreen("Hello, World!")
# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS
fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def print_six(row, format, end="\n"):
for col in range(6):
color = row*6 + col - 2
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(end=" ") # four spaces
print(end=end)
for row in range(0, 43):
print_six(row, fg, " ")
print_six(row, bg)
# Simple usage: print(fg("text", 160))
Try it online
I have a library called colorit. It is super simple.
Here are some examples:
from colorit import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()
# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))
# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))
# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))
# Combination
print(
background(
color("This text is blue with a white background", Colors.blue), Colors.white
)
)
# If you are using Windows Command Line, this is so that it doesn't close immediately
input()
This gives you:
It's also worth noting that this is cross platform and has been tested on Mac, Linux, and Windows.
You might want to try it out: https://github.com/SuperMaZingCoder/colorit
colorit is now available to be installed with PyPi! You can install it with pip install color-it on Windows and pip3 install color-it on macOS and Linux.
On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.
To see complete code that supports both ways, see the color console reporting code from Testoob.
ctypes example:
import ctypes
# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED = 0x0004 # text color contains red.
def get_csbi_attributes(handle):
# Based on IPython's winconsole.py, written by Alexander Belchenko
import struct
csbi = ctypes.create_string_buffer(22)
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
assert res
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
return wattr
handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)
I have wrapped joeld's answer into a module with global functions that I can use anywhere in my code.
File: log.py
def enable():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = "\033[1m"
def disable():
HEADER = ''
OKBLUE = ''
OKGREEN = ''
WARNING = ''
FAIL = ''
ENDC = ''
def infog(msg):
print(OKGREEN + msg + ENDC)
def info(msg):
print(OKBLUE + msg + ENDC)
def warn(msg):
print(WARNING + msg + ENDC)
def err(msg):
print(FAIL + msg + ENDC)
enable()
Use as follows:
import log
log.info("Hello, World!")
log.err("System Error")
def black(text):
print('\033[30m', text, '\033[0m', sep='')
def red(text):
print('\033[31m', text, '\033[0m', sep='')
def green(text):
print('\033[32m', text, '\033[0m', sep='')
def yellow(text):
print('\033[33m', text, '\033[0m', sep='')
def blue(text):
print('\033[34m', text, '\033[0m', sep='')
def magenta(text):
print('\033[35m', text, '\033[0m', sep='')
def cyan(text):
print('\033[36m', text, '\033[0m', sep='')
def gray(text):
print('\033[90m', text, '\033[0m', sep='')
black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")
Try online
Here is my modern (2021) solution: yachalk
It is one of the few libraries that properly supports nested styles:
Apart from that yachalk is auto-complete-friendly, has 256/truecolor support, comes with terminal-capability detection, and is fully typed.
Here are some design decision you may consider for choosing your solution.
High-level libraries vs low-level libraries / manual style handling?
Many answers to this question demonstrate how to ANSI escape codes directly, or suggest low-level libraries that require manual style enabling/disabling.
These approaches have subtle issues: Inserting on/off styles manually is
more verbose syntactically, because resets have to be specified explicitly,
more error prone, because you can accidentally forget to reset a style,
fails to get edge cases right: For instance in some terminals it is necessary to reset styles before newlines, and re-activate them after the line break. Also, some terminal have problems with simply overriding mutually exclusive styles, and require inserting "unnecessary" reset codes. If a developer's local terminal doesn't have these quirks, the developer will not discover these quirks immediately. The issue will only be reported later by others or cause problems e.g. on CI terminals.
Therefore if compatibility with many terminals is a goal, it's best to use a high-level library that offers automatic handling of style resets. This allows the library to take care of all edge cases by inserting the "spurious" ANSI escape codes where needed.
Why yet another library?
In JavaScript the de-facto standard library for the task is chalk, and after using it for a while in JS projects, the solutions available in the Python world were lacking in comparison. Not only is the chalk API more convenient to use (fully auto-complete compatible), it also gets all the edge cases right.
The idea of yachalk is to bring the same convenience to the Python ecosystem. If you're interested in a comparison to other libraries I've started feature comparison on the projects page. In addition, here is a long (but still incomplete) list of alternatives that came up during my research -- a lot to choose from :)
colored
ansicolors
termcolor
colorama
sty
blessings
rich
colorit
colorprint
console-color
pyfance
couleur
style (formerly known as clr)
pychalk
simple-chalk
chlk
chalky
constyle
I ended up doing this, and I felt it was cleanest:
formatters = {
'RED': '\033[91m',
'GREEN': '\033[92m',
'END': '\033[0m',
}
print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)
For Windows you cannot print to console with colors unless you're using the Win32 API.
For Linux it's as simple as using print, with the escape sequences outlined here:
Colors
For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:
#
Stupidly simple, based on joeld's answer:
class PrintInColor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
#classmethod
def red(cls, s, **kwargs):
print(cls.RED + s + cls.END, **kwargs)
#classmethod
def green(cls, s, **kwargs):
print(cls.GREEN + s + cls.END, **kwargs)
#classmethod
def yellow(cls, s, **kwargs):
print(cls.YELLOW + s + cls.END, **kwargs)
#classmethod
def lightPurple(cls, s, **kwargs):
print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
#classmethod
def purple(cls, s, **kwargs):
print(cls.PURPLE + s + cls.END, **kwargs)
Then just
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')
Building on joeld's answer, using https://pypi.python.org/pypi/lazyme
pip install -U lazyme:
from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc
Screenshot:
Some updates to the color_print with new formatters, e.g.:
>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter,
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
Note: italic, fast blinking, and strikethrough may not work on all terminals, and they don't work on Mac and Ubuntu.
E.g.,
>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar
Screenshot:
Note how well the with keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):
from colorama import Fore, Style
import sys
class Highlight:
def __init__(self, clazz, color):
self.color = color
self.clazz = clazz
def __enter__(self):
print(self.color, end="")
def __exit__(self, type, value, traceback):
if self.clazz == Fore:
print(Fore.RESET, end="")
else:
assert self.clazz == Style
print(Style.RESET_ALL, end="")
sys.stdout.flush()
with Highlight(Fore, Fore.GREEN):
print("this is highlighted")
print("this is not")
You could use Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
You can use the Python implementation of the curses library:
curses — Terminal handling for character-cell displays
Also, run this and you'll find your box:
for i in range(255):
print i, chr(i)
Emoji
You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color.
But you can use emojis instead! for example, you can use⚠️ for warning messages and 🛑 for error messages.
Or simply use these notebooks as a color:
📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color
🎁 Bonus:
This method also helps you to quickly scan and find logs directly in the source code.
But some operating systems (including some Linux distributions in some version with some window managers) default emoji font is not colorful by default and you may want to make them colorful, first.
How to open emoji picker?
mac os: control + command + space
windows: win + .
linux: control + . or control + ;
If you are programming a game perhaps you would like to change the background color and use only spaces? For example:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
An easier option would be to use the cprint function from the termcolor package.
It also supports %s, %d format of printing:
Results can be terminal dependant, so review the Terminal Properties section of the package documentation.
Windows Command Prompt and Python IDLE don't work
JupyterLab notebook does work
YAY! Another version
While I find this answer useful, I modified it a bit. This GitHub Gist is the result
Usage
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
In addition, you can wrap common usages:
print colors.error('sorry, ')
https://gist.github.com/Jossef/0ee20314577925b4027f

Categories

Resources