如何在Python中打印终端中的彩色文本?

时间:2008-11-13 18:58:11

标签: python unicode terminal ansi-colors

如何在Python中将彩色文本输出到终端? 表示实体块的最佳Unicode符号是什么?

54 个答案:

答案 0 :(得分:1530)

这在某种程度上取决于您所使用的平台。最常见的方法是打印ANSI转义序列。举一个简单的例子,这里是blender build scripts的一些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

这适用于包括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是“块字符”。

一些现代的基于文本的程序,例如“矮人要塞”,在图形模式下模拟文本模式,并使用经典PC字体的图像。您可以在Dwarf Fortress Wiki上找到一些可以使用的位图(user-made tilesets)。

Text Mode Demo Contest有更多资源用于在文本模式下进行图形处理。

嗯..我觉得这个答案有点过分了。不过,我正在计划一个史诗般的基于文本的冒险游戏。祝你的彩色文字好运!

答案 1 :(得分:653)

我很惊讶没有人提到Python termcolor module。用法非常简单:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

或者在Python 3中:

print(colored('hello', 'red'), colored('world', 'green'))

然而,对于游戏编程和你想要做的“彩色积木”,它可能不够复杂......

答案 2 :(得分:573)

答案 3 :(得分:350)

打印一个开始颜色/样式的字符串,然后打印字符串,然后使用'\x1b[0m'结束颜色/样式更改:

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

Success with green background example

使用以下代码获取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()

亮暗示例(完整)

enter image description here

黑暗照明示例(部分)

top part of output

答案 4 :(得分:134)

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

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

这会在bash urxvt中产生以下内容,并采用Zenburn风格的配色方案:

output colors

通过预防,我们可以获得更多颜色:

color matrix

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

这样我们就可以创建一个完整的颜色集合了:

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'

以下是生成测试的代码:

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

答案 5 :(得分:77)

您想了解ANSI转义序列。这是一个简短的例子:

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

有关详细信息,请参阅http://en.wikipedia.org/wiki/ANSI_escape_code

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

之类的unicode字符
print u"\u2588"

全部放在一起:

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

答案 6 :(得分:59)

我最喜欢的方式是使用Blessings库(完全披露:我写了它)。例如:

from blessings import Terminal

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

要打印彩色砖块,最可靠的方法是使用背景颜色打印空间。我使用这种技术在nose-progressive中绘制进度条:

print t.on_green(' ')

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

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

如果您在游戏过程中不得不使用其他终端功能,那么您也可以这样做。您可以使用Python的标准字符串格式来保持其可读性:

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

Blessings的好处在于它尽力在各种终端上工作,而不仅仅是(绝大多数)ANSI颜色的终端。它还保留了代码中不可读的转义序列,同时保持简洁易用。玩得开心!

答案 7 :(得分:49)

使用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'

答案 8 :(得分:42)

试试这个简单的代码

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

答案 9 :(得分:33)

sty与colorama类似,但它不那么冗长,支持8bit24bit(rgb)颜色,允许您注册自己的颜色,非常灵活并且记录良好。

from sty import fg, bg, ef, rs, RgbFg

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.set_style('orange', RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

打印:

enter image description here

<强>演示: enter image description here

答案 10 :(得分:28)

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

要查看支持这两种方式的完整代码,请参阅color console reporting code中的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)

答案 11 :(得分:23)

根据@ 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')

答案 12 :(得分:21)

我已将@joeld答案包装到具有全局函数的模块中,我可以在代码中的任何位置使用它。

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

答案 13 :(得分:20)

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

对于Linux来说,它就像使用print一样简单,使用此处列出的转义序列:

Colors

对于像盒子一样打印的字符,它实际上取决于您用于控制台窗口的字体。磅符号效果很好,但它取决于字体:

#

答案 14 :(得分:18)

在@joeld答案的基础上,使用https://pypi.python.org/pypi/lazyme while ((big = big + 1) && big < nb)

while (big++ < nb)

截图:

enter image description here

使用新格式化程序对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'] italic可能不适用于所有终端,不能在Mac / Ubuntu上运行。

E.g。

fast blinking

截图:

enter image description here

答案 15 :(得分:17)

我最终做到了这一点,我觉得这是最干净的:

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)

答案 16 :(得分:16)

请注意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")

答案 17 :(得分:16)

我知道我迟到了。但是,我有一个library called ColorIt。这非常简单。

以下是一些示例:

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

这给您:

Picture of ColorIt

还值得注意的是,这是跨平台的,并且已经在Mac,Linux和Windows上进行了测试。

您可能想尝试一下:https://github.com/CodeForeverAndEver/ColorIt

注意:几天后将添加闪烁,斜体,粗体等。

答案 18 :(得分:16)

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

另外,运行这个,你会找到你的盒子:

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

答案 19 :(得分:15)

您可以使用CLINT:

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

Get it from GitHub

答案 20 :(得分:14)

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

答案 21 :(得分:12)

如果您正在编写游戏,或许您想要更改背景颜色并仅使用空格?例如:

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

答案 22 :(得分:10)

如果您使用的是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 ... ")

答案 23 :(得分:10)

asciimatics为构建文本UI和动画提供了便携式支持:

#!/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:

rainbow-colored text among ascii noise

答案 24 :(得分:9)

Rich是一个相对较新的Python库,用于在终端中处理颜色。

在Rich中,有几种处理颜色的方法。最快的入门方法是丰富的打印方法,该方法可将bbcode之类的语法呈现到ANSI控制代码中:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

还有其他通过Rich(正则表达式,语法)和相关格式设置功能应用颜色的方法。

Screenshot of Rich

答案 25 :(得分:9)

另一个包装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'])

输出“Hello,world!”用蓝色的单词和感叹号加粗的红色和闪烁。

答案 26 :(得分:9)

YAY!另一个版本

虽然我发现this回答有用,但我修改了一下。这个Github Gist是结果

<强>使用

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

enter image description here

此外,您可以包装常用用法:

print colors.error('sorry, ')

asd

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

答案 27 :(得分:9)

这是一个诅咒示例:

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)

答案 28 :(得分:9)

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

答案 29 :(得分:8)

一个更简单的选择是使用cprint包中的termcolor函数。

color-print-python

它还支持%s, %d格式的打印

enter image description here

答案 30 :(得分:8)

我认为这是最简单的方法。只要您具有所需颜色的rgb值,就可以使用:

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)

打印红色文本的示例:

text = 'Hello, World'
colored_text = colored(255, 0, 0, text)
print(colored_text)

#or

print(colored(255, 0, 0, 'Hello, World'))

彩色文本

text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)

希望这会有所帮助

答案 31 :(得分:8)

如果您使用Django

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

快照:

image

(我通常在runserver终端上使用彩色输出进行调试,所以我添加了它。)

<子> 您可以测试它是否已安装在您的机器中:
$ python -c "import django; print django.VERSION"
要安装它,请检查:How to install Django

试一试!!

答案 32 :(得分:7)

import click

click.secho('Hello World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)

click (CLI library)有一个非常方便的方法,如果您正在编写命令行工具,则值得考虑。

答案 33 :(得分:7)

我之所以做出回应,是因为我找到了一种在Windows上使用ANSI代码的方法,以便您无需任何模块即可更改文本的颜色:

完成此操作的行是os.system('color'),但是要确保如果此人不在Windows上,也可以确保不会出现错误,则可以使用以下脚本:

import os, sys

if sys.platform.lower() == "win32":
    os.system('color')

# Group of Different functions for different styles
class style():
    BLACK = lambda x: '\033[30m' + str(x)
    RED = lambda x: '\033[31m' + str(x)
    GREEN = lambda x: '\033[32m' + str(x)
    YELLOW = lambda x: '\033[33m' + str(x)
    BLUE = lambda x: '\033[34m' + str(x)
    MAGENTA = lambda x: '\033[35m' + str(x)
    CYAN = lambda x: '\033[36m' + str(x)
    WHITE = lambda x: '\033[37m' + str(x)
    UNDERLINE = lambda x: '\033[4m' + str(x)
    RESET = lambda x: '\033[0m' + str(x)

print(style.YELLOW("Hello, ") + style.RESET("World!"))

Python版本: 3.6.7(32位)

答案 34 :(得分:6)

表情符号

您可以像在答案中提到的其他颜色那样为文本使用颜色,以使彩色文本具有背景或前景色。

但是您可以改用表情符号!例如,您可以将⚠️用于警告消息,将?用于错误消息。

或者只是将这些笔记本用作颜色:

?: error message
?: warning message
?: ok status message
?: action message
?: canceled status message
?: Or anything you like and want to recognize immediately by color

?奖励:

此方法还可以帮助您快速直接在源代码中直接扫描并查找日志

但是Linux默认的emoji字体默认情况下不是彩色的,您可能首先要使其彩色。

答案 35 :(得分:6)

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

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

答案 36 :(得分:6)

我建议这个新图书馆印刷 刚刚发布了1.2.0版作为跨平台库。

签出: Printy on github

它基于标志,因此您可以做类似的事情

from printy import printy

# with global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text
printy("Hello world", "rBU")

# with inline formats, this will apply a dim(D)
#blue (b) to the word 'Hello' and a striked (S)
#yellow (y) to the word 'world', the rest will remain as the predefined format
printy("this is a [bD]Hello@ [yS]world@ text")

enter image description here

答案 37 :(得分:5)

如果您只想使用内置包,请遵循以下结构:

实际上,我增强了 Mohamed Samy 答案,它现在负责多个输入以及数字。此外,它还支持其他 print() 参数,例如 end=。此外,我还添加了一个 .store() 方法,以便将日志也写入文件。

您可以创建一个实用程序以在代码中的任何位置使用它:

# utility.py

from datetime import datetime

class ColoredPrint:
    def __init__(self):
        self.PINK = '\033[95m'
        self.OKBLUE = '\033[94m'
        self.OKGREEN = '\033[92m'
        self.WARNING = '\033[93m'
        self.FAIL = '\033[91m'
        self.ENDC = '\033[0m'

    def disable(self):
        self.PINK = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

    def store(self):
        date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open('logfile.log', mode='a') as file_:
            file_.write(f"{self.msg} -- {date}")
            file_.write("\n")

    def success(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.OKGREEN + self.msg + self.ENDC, **kwargs)
        return self

    def info(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.OKBLUE + self.msg + self.ENDC, **kwargs)
        return self

    def warn(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.WARNING + self.msg + self.ENDC, **kwargs)
        return self

    def err(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.FAIL + self.msg + self.ENDC, **kwargs)
        return self

    def pink(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.PINK + self.msg + self.ENDC, **kwargs)
        return self

例如

from utility import ColoredPrint

log = ColoredPrint()

log.success("Hello" , 123, "Bye").store()
log.info("Hello" , 123, "Bye")
log.warn("Hello" , 123, "Bye")
log.err("Hello" , 123, "Bye").store()
log.pink("Hello" , 123, "Bye")

出:

enter image description here


[更新]:

现在,它的 PyPI package? 可用:

pip install python-colored-print

答案 38 :(得分:5)

我创建了一个项目(console-color,并且已经将其发布到PyPI

您可以扔pip install console-color来安装它。

然后用Sphinx-read-the-doc编写文档,请参见here

您可以从google-colab

获取更多示例

我仍然发布一些示例来吸引用户单击上面的链接:

# cprint is something like below
# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')
# where T_RGB = Union[Tuple[int, int, int], str] for example, you can input (255, 0, 0) or '#ff0000' or 'ff0000' they are ok
# The Style you can input the ``Style.`` (IDE will help you to choose you wanted)

# from console_color import RGB, Fore, Style, cprint, create_print
from console_color import *  

cprint("Hello World", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)
cprint("Hello World", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)

enter image description here

当然,您不必输入所有参数。您可以只添加所需的属性。


说实话,这个项目并不特殊,它仅使用f"\033[{target};2;{r};{g};{b}m{text}{style}" 目标是38或48,文本是您的输入字符串,样式是'\ 33 [0m“,'\ 33 [1m” ...'\ 033 [9m”之类的东西。

而且我只是使其易于使用(至少对我来说是这样)

希望它可以对某人有所帮助。

答案 39 :(得分:3)

我写了一个处理Linux / OSX / Windows中颜色的模块。它支持所有平台上的所有16种颜色,您可以在不同的时间设置前景色和背景色,并且字符串对象可以为len()和.capitalize()等提供合理的结果。

https://github.com/Robpol86/colorclass

example on Windows cmd.exe

答案 40 :(得分:3)

对于字符

您的终端最有可能使用Unicode(通常是UTF-8编码)字符,因此只需选择合适的字体即可查看您喜欢的字符。 Unicode char U + 2588,我建议您使用“Full block”。

尝试以下方法:

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是您要使用的模块。请检查此tutorial

答案 41 :(得分:3)

这是一个简单的功能,我可以用它以彩色方式打印文本消息而不必记住ANSI代码,而是使用标准的RGB元组来定义前景色和背景色。

def print_in_color(txt_msg,fore_tupple,back_tupple,):
    #prints the text_msg in the foreground color specified by fore_tupple with the background specified by back_tupple 
    #text_msg is the text, fore_tupple is foregroud color tupple (r,g,b), back_tupple is background tupple (r,g,b)
    rf,bf,gf=fore_tupple
    rb,gb,bb=back_tupple
    msg='{0}' + txt_msg
    mat='\33[38;2;' + str(rf) +';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) +'m' 
    print(msg .format(mat))
    print('\33[0m') # returns default print color to back to black

# example of use using a message with variables
fore_color='cyan'
back_color='dark green'
msg='foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255),(0,127,127))

答案 42 :(得分:2)

我写了一个简单的模块,可在以下位置找到: http://pypi.python.org/pypi/colorconsole

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

答案 43 :(得分:2)

使用pyfancy这是在终端中进行颜色处理的简单方法!

示例:

print(pyfancy.RED + "Hello Red" + pyfancy.END)

答案 44 :(得分:2)

print("\033[1;32;40m Bright Green  \n")

1

答案 45 :(得分:2)

这是我的现代 (2021) 解决方案:yachalk

它是为数不多的正确支持嵌套样式的库之一:

enter image description here

除此之外,yachalk 是自动完成友好的,支持 256/真彩色,带有终端功能检测,并且是全类型的。

以下是您在选择解决方案时可能会考虑的一些设计决策。

高级库与低级库/手动样式处理?

此问题的许多答案演示了如何直接转义 ANSI 代码,或建议需要手动启用/禁用样式的低级库。

这些方法有一些微妙的问题:手动插入开/关样式是

  • 在语法上更冗长,因为必须明确指定重置,
  • 更容易出错,因为您可能会不小心忘记重置样式,
  • 未能正确处理边缘情况:例如,在某些终端中,需要在换行前重置样式,并在换行后重新激活它们。此外,某些终端在简单地覆盖互斥样式方面存在问题,并且需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题只会被其他人稍后报告或导致问题,例如在 CI 终端上。

因此,如果目标是与许多终端兼容,最好使用提供自动处理样式重置的高级库。这允许库通过在需要的地方插入“虚假”ANSI 转义码来处理所有边缘情况。

为什么是另一个图书馆?

在 JavaScript 中,该任务的事实上的标准库是 chalk,在 JS 项目中使用一段时间后,Python 世界中可用的解决方案相比之下缺乏。 chalk API 不仅使用起来更方便(完全自动完成兼容),而且还可以正确处理所有边缘情况。

yachalk 的想法是为 Python 生态系统带来同样的便利。如果您对与其他库的比较感兴趣,我已经在项目页面上开始了 feature comparison。此外,这里有一个很长(但仍然不完整)的替代清单,这些清单是我在研究期间提出的——很多可供选择:)

答案 46 :(得分:1)

一些解决方案,例如:

i

OR

result.addEventListener('click', function() {
  result.style.backgroundColor = colorArr[i]
  i = i+1
  if (i >= colorArr.length) {i = 0}
}

OR

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)

print(fg("text", 160))

在Windows 10终端或Power Shell窗口上

可能不起作用,或者在其他情况下它们可能无法直接起作用。

但是在程序的开头插入这两行可能会有所帮助:

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)


text = 'Hello, World'
colored_text = colored(255, 0, 0, text)
print(colored_text)

class Color: COLOR = [f"\33[{i}m" for i in range(44)] for i in range(44): print(Color.COLOR[i] + 'text') 允许您在终端中打印ANSI代码,该代码根据您的选择为输出着色(但是可能需要调用其他系统特定功能,才能在终端中打印彩色文本)。

答案 47 :(得分:1)

您可以使用任何语言提供的shell转义字符。 这些转义字符以ESC字符开头,后跟许多参数。

例如,在终端中输出红色Hello world字符串:

echo "\e[31m Hello world \e[0m"

或者从python脚本:

print("\e[31m Hello world \e[0m")

另外,我写了一篇关于Escape sequences的文章,可能有助于你更好地掌握这种机制。我希望它会对你有所帮助。

答案 48 :(得分:0)

我能找到的最简单的方法不是使用ANSI转义码,而是使用导入模块Fore中的colorama。看看下面的代码:

from colorama import Fore, Style

print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")

print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")

与ANSI转义代码相比:

print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")

print("BACK TO NORMALZ.")

答案 49 :(得分:0)

我是python的菜鸟,每次发现这样的主题时,我都会感到兴奋。但是这次(突然)我觉得我有话要说。特别是因为几分钟前,我在python中发现了一个WOW东西(至少现在对我而言):

Context Managers

from contextlib import contextmanager
#   FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
#   BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

@contextmanager
def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  yield
  print("{prefix}0m".format(prefix=prefix))

with printESC('\x1B[', REDFC, 'Colored Text'):
  pass

EXAMPLE

或类似这样:

#   FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
#   BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  print("{prefix}0m".format(prefix=prefix))

printESC('\x1B[', REDFC, 'Colored Text')

答案 50 :(得分:0)

为了解决这个问题,我创建了一个令人费解的简单包,用于打印带有插值颜色代码的字符串,称为icolor

icolor包含两个函数:cformatcprint,每个函数都带有一个带有子串的字符串,这些子串被内插以映射到ANSI转义序列,例如。

from icolor import cformat # there is also cprint

cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'

包含所有ANSI颜色(例如#RED;#BLUE;等),以及#RESET;#BOLD;等。

背景颜色的前缀为x,因此绿色背景为#xGREEN;

可以使用#逃脱##

鉴于其简单性,最好的文档可能是the code itself

它是on PYPI,因此可以sudo easy_install icolor

答案 51 :(得分:0)

我的两分钱(PyColorTerm):

安装:

sudo apt-get install python-pip
pip install pycolorterm

Python脚本:

from pycolorterm import pycolorterm

with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
    out.write('Works OK!')

“工作正常!”以绿色显示。

答案 52 :(得分:0)

当我在寻找如何为日志着色时,我被谷歌搬到了那里:

彩色日志

安装

pip install coloredlogs

用法

最少使用:
import logging
import coloredlogs

coloredlogs.install()  # install a handler on the root logger

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

结果: minimal usage

从消息级调试开始:
import logging
import coloredlogs

coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

结果: debug level

隐藏库中的消息:
import logging
import coloredlogs

logger = logging.getLogger(__name__)  # get a specific logger object
coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
coloredlogs.install(level='DEBUG', logger=logger)  # pass a specific logger object

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

结果: debug level

格式化日志消息:
import logging
import coloredlogs

logger = logging.getLogger(__name__)  # get a specific logger object
coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
coloredlogs.install(level='DEBUG', logger=logger)  # pass a specific logger object
coloredlogs.install(
    level='DEBUG', logger=logger,
    fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s'
)

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

结果: format log messages

可用的格式属性:
  • %(asctime)s - 发出日志调用时作为人类可读字符串的时间
  • %(created)f - 发出日志调用时的浮动时间
  • %(filename)s - 文件名
  • %(funcName)s - 包含日志调用的函数名称
  • %(hostname)s - 系统主机名
  • %(levelname)s - 文本记录级别
  • %(levelno)s - 整数日志级别
  • %(lineno)d - 发出日志调用的行号
  • %(message)s - 传递给日志调用的消息(与 %(msg)s 相同)
  • %(module)s - 发出日志调用的不带扩展名的文件名
  • %(msecs)d - 发出日志记录调用时间的毫秒部分
  • %(msg)s - 传递给日志调用的消息(与 %(message)s 相同)
  • %(name)s - 记录器名称
  • %(pathname)s - 包含日志调用的文件的完整路径名
  • %(process)d - 进程 ID
  • %(processName)s - 进程名称
  • %(programname)s - 系统程序名
  • %(relativeCreated)d - 发出日志记录调用时的整数时间,相对于加载日志记录模块的时间
  • %(thread)d - 线程 ID
  • %(threadName)s - 线程名称
  • %(username)s - 系统用户名

来源:

Coloredlogs package

Logging library

答案 53 :(得分:-1)

这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。

此答案还使用了 PythonRich,该库在之前对此问题的回答中简要介绍过。在这个答案中,我使用函数 rich.color.ANSI_COLOR_NAMES 来获取将用于突出显示预定义搜索词的随机颜色列表。

import random
import re as regex
from rich import color
from rich import print


def create_dynamic_regex(search_words):
    """
    This function is used to create a dynamic regular expression
    string and a list of random colors. Both these elements will
    be used in the function colorize_text()

    :param search_words: list of search terms
    :return: regular expression search string and a list of colors
    :rtype: string, list
    """
    colors_required = create_list_of_colors(len(search_words))
    number_of_search_words = len(search_words)
    combined_string = ''
    for search_word in search_words:
        number_of_search_words -= 1
        if number_of_search_words != 0:
            current_string = ''.join(r'(\b' + search_word + r'\b)|')
            combined_string = (combined_string + current_string)
        elif number_of_search_words == 0:
            current_string = ''.join(r'(\b' + search_word + r'\b)')
            combined_string = (combined_string + current_string)
    return combined_string, colors_required


def random_color():
    """
    This function is used to create a random color using the
    Python package rich.
    :return: color name
    :rtype: string
    """
    selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))
    return selected_color


def create_list_of_colors(number_of_colors):
    """
    This function is used to generate a list of colors,
    which will be used in the function colorize_text()
    :param number_of_colors:
    :return: list of colors
    :rtype: list
    """
    list_of_colors = [random_color() for _ in range(number_of_colors)]
    return list_of_colors


def colorize_text(text, regex_string, array_of_colors):
    """
    This function is used to colorize specific words in a text string.
    :param text: text string potentially containing specific words to colorize.
    :param regex_string: regular expression search string
    :param array_of_colors: list of colors
    :return: colorized text
    :rtype: string
    """
    available_colors = array_of_colors
    word_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)
    i = 0
    output = ""
    for word in word_regex.finditer(text):
        get_color = available_colors[word.lastindex - 1]
        output += "".join([text[i:word.start()],
                           "[%s]" % available_colors[word.lastindex - 1],
                           text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])
        i = word.end()
    return ''.join([output, text[word.end():]])


def generate_console_output(text_to_search, words_to_find):
    """
    This function is used generate colorized text that will
    be outputting to the console.

    :param text_to_search: text string potentially containing specific words to colorize.
    :param words_to_find: list of search terms.
    :return: A string containing colorized words.
    :rtype: string
    """
    search_terms, colors = create_dynamic_regex(words_to_find)
    colorize_html = colorize_text(text_to_search, search_terms, colors)
    print(colorize_html)


text = "The dog chased the cat that was looking for the mouse that the dog was playing with."
words = ['dog', 'cat', 'mouse']
generate_console_output(text, words)

这是上面代码的打印输出:

enter image description here

我创建了两个 GIST 来为文本着色。