在颜色的terminal打印?

如何在Python中输出彩色文本到terminal? 什么是代表固体块的最好的Unicode符号?

这有点取决于你在哪个平台上。 最常见的方法是打印ANSI转义序列。 举个简单的例子,下面是一些来自搅拌机构build脚本的 python代码:

 class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' 

要使用这样的代码,你可以做类似的事情

 print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC 

这将适用于unix,包括OS X,Linux和Windows(如果使用ANSICON ,或者在启用VT100仿真的 Windows 10中)。 有设置颜色,移动光标等的ansi代码。

如果你打算使这个变得复杂(而且听起来像是在编写游戏),那么你应该看看“curses”模块,它为你处理了很多复杂的部分。 Python Curses HowTO是一个很好的介绍。

如果你没有使用扩展的ASCII(即不在PC上),那么你的ASCII码字符就会低于127,'#'或'@'可能是你最好的select。 如果您可以确保您的terminal正在使用IBM 扩展的ASCII字符集 ,则还有更多的选项。 字符176,177,178和219是“块字符”。

一些现代的基于文本的程序,如“矮人堡垒”,在graphics模式下模拟文本模式,并使用经典PC字体的图像。 你可以find一些你可以在Dwarf Fortress Wiki上看到的位图( 用户制作的tilesets )。

文本模式演示比赛有更多的资源在文本模式下做graphics。

嗯..我觉得这个答案有点让人失望。 虽然我正在计划一个史诗般的基于文本的冒险游戏。 祝你好运彩色文字!

我很惊讶没有人提到过Python的termcolor模块 。 用法很简单:

 from termcolor import colored print colored('hello', 'red'), colored('world', 'green') 

然而,对于游戏编程和你想要做的“彩色块”来说,它可能不够复杂。

Python的所有跨平台着色的答案是Colorama 。

打印一个string,开始一个颜色/样式,然后是string,然后用'\x1b[0m'结束颜色/样式的改变:

 print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m') 

成功与绿色背景的例子

使用以下代码获取shell文本的格式选项表:

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

光明黑暗的例子(完整)

在这里输入图像描述

暗光示例(部分)

输出的顶部

您想了解ANSI转义序列。 这里有一个简单的例子:

 CSI="\x1B[" reset=CSI+"m" print CSI+"31;40m" + "Colored Text" + CSI + "0m" 

欲了解更多信息,请参阅http://en.wikipedia.org/wiki/ANSI_escape_code

对于块字符,请尝试使用unicode字符,例如\ u2588:

 print u"\u2588" 

把它放在一起:

 print CSI+"31;40m" + u"\u2588" + CSI + "0m" 

我最喜欢的方式是与祝福图书馆(全面披露:我写了它)。 例如:

 from blessings import Terminal t = Terminal() print t.red('This is red.') print t.bold_bright_red_on_black('Bright red on black') 

要打印彩色砖块,最可靠的方法是打印带有背景颜色的空间。 我使用这种技术来绘制渐进式的进度条 :

 print t.on_green(' ') 

您也可以在特定位置打印:

 with t.location(0, 5): print t.on_yellow(' ') 

如果您在游戏过程中必须使用其他terminalfunction,那么也可以这样做。 您可以使用Python的标准string格式来保持其可读性:

 print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t) 

祝福的好处在于,它尽力在各种terminal上工作,而不仅仅是(绝大多数常见的)ANSI颜色的terminal。 它还保留了不可读的转义序列,同时保持简洁的使用。 玩的开心!

试试这个简单的代码

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

使用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. ie colors.fg.red or colors.bg.green also, the generic bold, disable, underline, reverse, strikethrough, and invisible work with the main class ie 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' 

定义一个开始颜色的string和一个结束颜色的string,然后打印文本,起始string在前面,结束string在结尾。

 CRED = '\033[91m' CEND = '\033[0m' print(CRED + "Error, does not compute!" + CEND) 

这在bash产生以下结果,在urxvt使用Zenburn风格的配色scheme:

输出颜色

通过exremintation,我们可以得到更多的颜色:

颜色矩阵

注意: \33[5m\33[6m正在闪烁。

这样我们可以创build一个全彩色的集合:

 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' 

这里是生成testing的代码:

 for i in range(24): colors = "" for j in range(5): colors = colors + "\33["+str(x+j)+"m\\33["+str(x+j)+"m\033[0m " print(colors) x=x+ 

在Windows上,您可以使用模块“win32console”(可用于某些Python发行版)或模块“ctypes”(Python 2.5及更高版本)来访问Win32 API。

要查看支持两种方式的完整代码,请参阅Testoob的颜色控制台报告代码 。

ctypes例子:

 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) 

根据@ joeld的回答愚蠢简单

 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) 

然后就是

 PrintInColor.red('hello', end=' ') PrintInColor.green('world') 

我已经将@joeld答案包装到一个全局函数模块中,我可以在代码中的任何地方使用它。

文件:log.py

 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 

使用方法如下:

  import log log.info("Hello World") log.err("System Error") 

我使用colorama模块进行Python中的彩色terminal打印。 链接在这里http://pypi.python.org/pypi/colorama

打印红色和绿色文本的一些示例代码:

 from colorama import * print(Fore.GREEN + 'Green text') print(Fore.RED + 'Red text') 

我用colorama写一个基本的matrix程序

在Ubuntu上安装(您的发行版安装命令可能不同)

 sudo apt-get install python-pip sudo pip install colorama 

使用ANSI

 RED = '\033[91m' GREEN = '\033[92m' YELLOW = '\033[93m' LIGHT_PURPLE = '\033[94m' PURPLE = '\033[95m' END = '\033[0m' 

使你的function: –

 def red(name): print ("\033[91m {}\033[00m" .format(name)) 

通话function: –

红色(“好的”)好的< – 它会打印在红色,

注意: – 不需要任何模块

对于Windows,除非使用win32api,否则无法使用颜色进行控制台打印。

对于Linux来说,就像使用print一样简单,这里列出了转义序列:

颜色

对于字符打印像一个盒子,这真的取决于你用于控制台窗口的字体。 英镑符号运作良好,但它取决于字体:

 # 

注意with关键字与这些需要重置的修饰符(使用Python 3和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") 

您可以使用curses库的Python实现: http : //docs.python.org/library/curses.html

另外,运行这个,你会发现你的盒子:

 for i in range(255): print i, chr(i) 

你可以使用CLINT :

 from clint.textui import colored print colored.red('some warning message') print colored.green('nicely done!') 

从GitHub获取它 。

我最终这样做,我觉得它是最干净的:

 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) 

build立@joeld答案,使用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 

截图:

在这里输入图像描述


使用新的格式化程序对color_print进行一些更新,例如:

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

注意: italicfast blinkingstrikethrough可能无法在所有terminal上运行,在Mac / Ubuntu上不起作用。

例如

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

截图:

在这里输入图像描述

如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格? 例如:

 print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m" 

这是一个诅咒的例子:

 import curses def main(stdscr): stdscr.clear() if curses.has_colors(): for i in xrange(1, curses.COLORS): curses.init_pair(i, i, curses.COLOR_BLACK) stdscr.addstr("COLOR %d! " % i, curses.color_pair(i)) stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD) stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT) stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE) stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK) stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM) stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE) stdscr.refresh() stdscr.getch() if __name__ == '__main__': print "init..." curses.wrapper(main) 

好极了! 另一个版本

而我觉得这个答案有用,我修改了一下。 这Github Gist是结果

用法

 print colors.draw("i'm yellow", bold=True, fg_yellow=True) 

在这里输入图像描述

另外你可以包装常用的用法:

 print colors.error('sorry, ') 

ASD

https://gist.github.com/Jossef/0ee20314577925b4027f

https://raw.github.com/fabric/fabric/master/fabric/colors.py

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

如果你正在使用Windows,那么你在这里!

 # 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 ... ") 

如果你正在使用Django

 >>> from django.utils.termcolors import colorize >>> print colorize("Hello World!", fg="blue", bg='red', ... opts=('bold', 'blink', 'underscore',)) Hello World! >>> help(colorize) 

快照:

图片

(我通常使用彩色输出在runserverterminal上进行debugging,所以我添加了它。)

您可以testing它是否安装在您的机器上:
$ python -c "import django; print django.VERSION"
要安装它,请检查: 如何安装Django

试一试!!

另一个包装python 3打印函数的pypi模块:

https://pypi.python.org/pypi/colorprint

如果您也from __future__ import print它可以在Python 2.x中使用。 这是来自模块pypi页面的一个python 2例子:

 from __future__ import print_function from colorprint import * print('Hello', 'world', color='blue', end='', sep=', ') print('!', color='red', format=['bold', 'blink']) 

输出“你好,世界!” 用蓝色和惊叹号大胆的红色和闪烁的话。

asciimatics为构build文本UI和animation提供了便携式支持:

 #!/usr/bin/env python from asciimatics.effects import RandomNoise # $ pip install asciimatics from asciimatics.renderers import SpeechBubble, Rainbow from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.exceptions import ResizeScreenError def demo(screen): render = Rainbow(screen, SpeechBubble('Rainbow')) effects = [RandomNoise(screen, signal=render)] screen.play([Scene(effects, -1)], stop_on_resize=True) while True: try: Screen.wrapper(demo) break except ResizeScreenError: pass 

Asciicast:

在ascii噪声之中的彩虹色的文本

我写了一个简单的模块,可在http://pypi.python.org/pypi/colorconsole

它适用于Windows,Mac OS X和Linux。 它在Linux和Mac上使用ANSI,但在Windows上使用本机调用控制台function。 你有颜色,光标定位和键盘input。 它不是诅咒的替代品,但是如果您需要在简单的脚本或ASCII游戏中使用,它可能非常有用。

对于人物

你的terminal很可能使用Unicode(通常是UTF-8编码)字符,所以只需要select合适的字体就可以看到你喜欢的字符。 Unicode字符U + 2588,“全块”是我build议你使用的。

尝试以下操作:

 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是你想要使用的模块。 检查这个教程 。

Interesting Posts