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:
print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)
or, with Python3.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).
Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!
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()
Print a string that starts a color/style, then the string, 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 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()
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:
import os
os.system("")# Group of Different functions for different stylesclass 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!")
I’m responding because I have found out a way to use ANSI codes on Windows 10, so that you can change the colour of text without any modules that aren’t built in:
The line that makes this work is os.system(""), or any other system call, which allows you to print ANSI codes in the Terminal:
import os
os.system("")
# Group of Different functions for 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: Although this gives the same options as other Windows options, Windows does not full support ANSI codes, even with this trick. Not all the text decoration colours work and all the ‘bright’ colours (Codes 90-97 and 100-107) display the same as the regular colours (Codes 30-37 and 40-47)
Edit: Thanks to @j-l for finding an even shorter method.
tl;dr: Add os.system("") near the top of your file.
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!
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 importStyle,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')
sty is similar to colorama, but it’s less verbose, supports 8bit and 24bit (rgb) colors, allows you to register your own styles, supports muting, 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')
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'
generated a class with all the colors using a for loop to iterate every combination of color up to 100, 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'
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 Belchenkoimport 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)
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:
#
回答 15
# 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 -2if color>=0:
text ="{:3d}".format(color)print(format(text,color), end=" ")else:print(end=" ")# four spacesprint(end=end)for row in range(0,43):
print_six(row, fg," ")
print_six(row, bg)# Simple usage: print(fg("text", 160))
# 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))
回答 16
我最终这样做了,我觉得那是最干净的:
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)
fromColorItimport*# Use this to ensure that ColorIt will be usable by certain command line interfaces
initColorIt()# Foregroundprint(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))# Backgroundprint(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))# Customprint(color ("This color has a custom grey text color",(150,150,150))print(background ("This color has a custom grey background",(150,150,150))# Combinationprint(background (color ("This text is blue with a white background", colors.BLUE), colors.WHITE))
from ColorIt import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces
initColorIt()
# 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))
This gives you:
It’s also worth noting that this is cross platform and has been tested on mac, linux, and windows.
Note: Blinking, italics, bold, etc. will be added in a few days.
回答 24
如果您使用的是Windows,那么就到这里!
# display text on a Windows console# Windows XP with Python27 or Python32from ctypes import windll
# needed for Python2/Python3 difftry:
input = raw_input
except:pass
STD_OUTPUT_HANDLE =-11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)# look at the output and select the color you want# for instance hex E is yellow on black# hex 1E is yellow on blue# hex 2E is yellow on green and so onfor color in range(0,75):
windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)print("%X --> %s"%(color,"Have a fine day!"))
input("Press Enter to go on ... ")
# display text on a Windows console
# Windows XP with Python27 or Python32
from ctypes import windll
# needed for Python2/Python3 diff
try:
input = raw_input
except:
pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# look at the output and select the color you want
# for instance hex E is yellow on black
# hex 1E is yellow on blue
# hex 2E is yellow on green and so on
for color in range(0, 75):
windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
print("%X --> %s" % (color, "Have a fine day!"))
input("Press Enter to go on ... ")
"""
.. versionadded:: 0.9.2
Functions for wrapping strings in ANSI color codes.
Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.
For example, to print some text as green on supporting terminals::
from fabric.colors import green
print(green("This text is green!"))
Because these functions simply return modified strings, you can nest them::
from fabric.colors import red, green
print(red("This sentence is red, except for " + \
green("these words, which are green") + "."))
If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""def _wrap_with(code):def inner(text, bold=False):
c = code
if bold:
c ="1;%s"% c
return"\033[%sm%s\033[0m"%(c, text)return inner
red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')
"""
.. versionadded:: 0.9.2
Functions for wrapping strings in ANSI color codes.
Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.
For example, to print some text as green on supporting terminals::
from fabric.colors import green
print(green("This text is green!"))
Because these functions simply return modified strings, you can nest them::
from fabric.colors import red, green
print(red("This sentence is red, except for " + \
green("these words, which are green") + "."))
If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""
def _wrap_with(code):
def inner(text, bold=False):
c = code
if bold:
c = "1;%s" % c
return "\033[%sm%s\033[0m" % (c, text)
return inner
red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')