如何在Python中将彩色文本输出到终端?
当前回答
对于字符
您的终端很可能使用Unicode(通常为UTF-8编码)字符,所以只需选择合适的字体即可看到您喜爱的字符。Unicode字符U+2588,“完整块”是我建议您使用的字符。
尝试以下操作:
import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
char= unichr(index)
try: its_name= unicodedata.name(char)
except ValueError: its_name= "N/A"
fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()
稍后使用您喜爱的查看器检查文件。
对于颜色
curses是您要使用的模块。查看本教程。
其他回答
还有Python termcolor模块。用法很简单:
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
或者在Python 3中:
print(colored('hello', 'red'), colored('world', 'green'))
然而,对于游戏编程和你想做的“彩色方块”来说,它可能不够复杂。。。
要使ANSI代码在windows上运行,请首先运行
os.system('color')
我使用for循环生成了一个包含所有颜色的类,将颜色的每个组合迭代到100,然后用Python颜色编写了一个类。复制并粘贴,GPLv2由我执行:
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'
如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
使用pyfancy。这是一种在终端中进行颜色处理的简单方法!
例子:
print(pyfancy.RED + "Hello Red" + pyfancy.END)
作为RGB标准的粉丝,我会这样做:
def color_text(text, rgb):
r, g, b = rgb
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
class rgb():
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# and so on ...
print(color_text("hello colored world", rgb.GREEN))
PS:受到CircuitSacul回答的强烈启发