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()
# Pure Python 3.x demo, 256 colors
# Works with bash under Linux
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):
for col in range(6):
color = row*6 + col + 4
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(" ", end=" ")
for row in range(-1,42):
print_six(row, fg)
print("",end=" ")
print_six(row, bg)
print()
"""
.. 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')
3
请注意 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")
7
我最终这样做了,我觉得它最干净:
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)
from sty import fg, bg, ef, rs, Rule
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 new colors:
fg.orange = Rule('rgb_fg', 255, 150, 50)
buf = fg.orange + 'Yay, Im orange.' + fg.rs
print(foo, bar, baz, qux, qui, buf, sep='\n')
打印:
Demo:
9
根据@ 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)
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'
527
如果你使用的是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 ... ")
30 回答
我很惊讶没人提到Python termcolor module . 用法非常简单:
或者在Python 3中:
然而,对于游戏编程和你想要做的“彩色块”来说,它可能不够复杂......
如果您正在编写游戏,或许您想要更改背景颜色并仅使用空格?例如:
我已将@joeld的答案包装到一个具有全局函数的模块中,我可以在代码中的任何位置使用它 .
file:log.py
用法如下:
我最喜欢的方式是使用Blessings库(完全披露:我写了它) . 例如:
要打印彩色砖块,最可靠的方法是打印带有背景颜色的空间 . 我使用这种技术在nose-progressive中绘制进度条:
您也可以在特定位置打印:
如果您在游戏过程中不得不使用其他终端功能,那么您也可以这样做 . 您可以使用Python的标准字符串格式来保持其可读性:
Blessings的好处在于它尽力在各种终端上工作,而不仅仅是(绝大多数)ANSI颜色的终端 . 它还会使代码中存在不可读的转义序列,同时保持简洁易用 . 玩得开心!
打印一个开始颜色/样式的字符串,然后打印字符串,然后使用
'\x1b[0m'
结束颜色/样式更改:使用以下代码获取shell文本的格式选项表:
亮暗示例(完整)
黑暗照明示例(部分)
你可以使用CLINT:
Get it from GitHub .
对于角色
您的终端最有可能使用Unicode(通常是UTF-8编码)字符,因此只需选择合适的字体即可查看您喜欢的字符 . Unicode char U 2588,我建议你使用“Full block” .
请尝试以下方法:
稍后使用您喜欢的查看器检查文件 .
对于颜色
curses是您要使用的模块 . 检查这个tutorial .
一个更简单的选择是使用
termcolor
包中的cprint
函数 .它还支持
%s, %d
格式的打印在Windows上,您可以使用模块'win32console'(在某些Python发行版中提供)或模块'ctypes'(Python 2.5及更高版本)来访问Win32 API .
要查看支持这两种方式的完整代码,请参阅Testoob中的color console reporting code .
ctypes示例:
定义一个开始颜色的字符串和一个结束颜色的字符串,然后使用前面的起始字符串和结尾处的结束字符串打印文本 .
这将在
bash
中产生以下内容,在urxvt
中具有Zenburn风格的配色方案:通过预防,我们可以获得更多颜色:
注意:
\33[5m
和\33[6m
正在闪烁 .这样我们就可以创建一个完整的颜色集合:
以下是生成测试的代码:
试试这个简单的代码
在@joeld答案的基础上,使用https://pypi.python.org/pypi/lazyme
pip install -U lazyme
:截图:
使用新格式化程序对
color_print
进行了一些更新,例如:注意:
italic
,fast blinking
和strikethrough
可能无法在所有终端上运行,不适用于Mac / Ubuntu .例如 .
截图:
对于Python中的所有跨平台着色,答案是Colorama .
Python 3.6示例屏幕截图:
https://raw.github.com/fabric/fabric/master/fabric/colors.py
请注意
with
关键字与需要重置的修饰符(使用Python 3和Colorama)的混合程度如何:我最终这样做了,我觉得它最干净:
您可以使用curses库的Python实现:http://docs.python.org/library/curses.html
此外,运行此,你会找到你的盒子:
asciimatics为构建文本UI和动画提供了便携式支持:
Asciicast:
如果您正在使用Django
快照:
(我通常使用彩色输出在runserver终端上进行调试,所以我添加了它 . )
您可以测试它是否已安装在您的计算机中:$ python -c“import django; print django.VERSION”要安装它,请检查:如何安装Django
试试看!!
sty类似于colorama,但它不那么冗长,支持8bit和24bit(rgb)颜色,允许您注册自己的颜色,非常灵活且记录良好 . 如果您不关心与90年代停留的终端仿真器的兼容性并希望使用新功能,您可能需要尝试一下 .
打印:
Demo:
根据@ joeld的回答,愚蠢的简单
然后就是
这在某种程度上取决于您所处的平台 . 最常见的方法是通过打印ANSI转义序列 . 举个简单的例子,这里有一些来自blender build scripts的python代码:
要使用这样的代码,你可以做类似的事情
这将适用于包括OS X,Linux和Windows的unix(如果您使用ANSICON,或者在Windows 10中,只要启用VT100 emulation) . 有ansi代码用于设置颜色,移动光标等 .
如果你要复杂化这个(如果你正在编写一个游戏,它听起来就像你一样),你应该查看"curses"模块,它可以为你处理很多复杂的部分 . Python Curses HowTO是一个很好的介绍 .
如果你没有使用扩展的ASCII(即不在PC上),那么你会遇到127以下的ascii字符,而'#'或'@'可能是你阻止的最佳选择 . 如果您可以确保您的终端使用的是IBM extended ascii character set,那么您还有更多选择 . 字符176,177,178和219是"block characters" .
一些现代的基于文本的程序,如"Dwarf Fortress",在图形模式下模拟文本模式,并使用经典PC字体的图像 . 您可以在Dwarf Fortress Wiki上找到一些可以使用的位图(参见user-made tilesets) .
Text Mode Demo Contest有更多资源用于在文本模式下执行图形 .
嗯......我觉得这个答案有点过分了 . 不过,我正在计划一个史诗般的基于文本的冒险游戏 . 祝你的彩色文字好运!
YAY!另一个版本
虽然我发现this回答有用,但我修改了一下 . 这是Github Gist的结果
usage
此外,您可以包装常见的用法:
https://gist.github.com/Jossef/0ee20314577925b4027f
您想了解ANSI转义序列 . 这是一个简短的例子:
有关详细信息,请参阅http://en.wikipedia.org/wiki/ANSI_escape_code
对于块字符,请尝试像\ u2588这样的unicode字符:
把它们放在一起:
另一个包装python 3打印功能的pypi模块:
https://pypi.python.org/pypi/colorprint
如果你也是
from __future__ import print
,它可以在python 2.x中使用 . 这是模块pypi页面中的python 2示例:输出“Hello,world!”用蓝色的字和感叹号大胆的红色和闪烁 .
使用for循环生成一个包含所有颜色的类,以迭代每个颜色组合,最多100个,然后用python颜色编写一个类 . 随意复制和粘贴,GPLv2由我:
如果你使用的是Windows,那么就去吧!
对于Windows,除非使用win32api,否则无法使用颜色打印到控制台 .
对于Linux来说,它就像使用print一样简单,其中包含了转义序列:
Colors
对于像盒子一样打印的字符,它实际上取决于您用于控制台窗口的字体 . 英镑符号效果很好,但它取决于字体:
这是一个curses示例: