标签归档:ansi-colors

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

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

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

How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?


回答 0

这在某种程度上取决于您所使用的平台。最常见的方法是打印ANSI转义序列。对于一个简单的示例,这是Blender构建脚本中的一些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)

或者,使用Python3.6 +:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

这将在包括OS X,Linux和Windows的Unix上运行(前提是您使用ANSICON,或者在Windows 10中,前提是您启用了VT100仿真)。有用于设置颜色,移动光标等的ansi代码。

如果您要对此进行复杂化处理(听起来就像是在编写游戏),则应查看“ curses”模块,该模块为您处理了许多复杂的部分。在Python的诅咒HOWTO是一个很好的介绍。

如果您没有使用扩展的ASCII码(即不在PC上),那么您将只能使用127以下的ASCII字符,而“#”或“ @”可能是您最好的选择。如果可以确保您的终端使用的是IBM 扩展的ascii字符集,那么您还有更多选择。字符176、177、178和219是“块字符”。

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

文本模式设计大赛已在文本模式下做图形更多的资源。

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

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:

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'

To use code like this, you can do something like

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

The Text Mode Demo Contest has more resources for doing graphics in text mode.

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!


回答 1

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

from termcolor import colored

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

或在Python 3中:

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

但是,对于游戏编程和您要执行的“彩色块”来说,它可能不够复杂…

I’m surprised no one has mentioned the Python termcolor module. Usage is pretty simple:

from termcolor import colored

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

Or in Python 3:

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

It may not be sophisticated enough, however, for game programming and the “colored blocks” that you want to do…


回答 2

答案是Colorama,用于Python中的所有跨平台着色。

Python 3.6示例屏幕截图:

The answer is Colorama for all cross-platform coloring in Python.

A Python 3.6 example screenshot:


回答 3

打印一个以颜色/样式开头的字符串,然后打印该字符串,然后通过以下命令结束颜色/样式更改'\x1b[0m'

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

使用以下代码获取外壳程序文本的格式选项表:

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

Light-on-dark example (complete)

Dark-on-light example (partial)


回答 4

定义一个以颜色开头的字符串和一个以颜色结尾的字符串,然后打印您的文本,其中起始字符串在前面,结尾字符串在结尾。

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

这会产生bash,并urxvt带有Zenburn风格的配色方案:

通过实验,我们可以获得更多的颜色:

注意:\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

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:

Through experimentation, we can get more colors:

Note: \33[5m and \33[6m are blinking.

This way we can create a full color collection:

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'

Here is the code to generate the test:

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

您想了解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")

You want to learn about ANSI escape sequences. Here’s a brief example:

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

For more info see http://en.wikipedia.org/wiki/ANSI_escape_code

For a block character, try a unicode character like \u2588:

print(u"\u2588")

Putting it all together:

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

回答 6

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

进行此工作的行是os.system("")或任何其他系统调用,它使您可以在终端中打印ANSI代码:

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

注意:尽管此选项与其他Windows选项具有相同的选项,但是Windows即使使用此技巧也无法完全支持ANSI代码。并非所有的文本装饰颜色都起作用,并且所有“明亮”颜色(代码90-97和100-107)显示的颜色与常规颜色相同(代码30-37和40-47)

编辑:感谢@jl查找更短的方法。

tl; dros.system("")在文件顶部附近添加。

Python版本: 3.6.7

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.

Python Version: 3.6.7


回答 7

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

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

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

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

Blessings的好处在于,它尽其所能在各种终端上工作,而不仅仅是(绝大多数)ANSI颜色终端。它还在使代码简洁明了的同时,将无法读取的转义序列保留在代码之外。玩得开心!

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!


回答 8

sty与colorama相似,但较为冗长,支持8位24位(rgb)颜色,允许您注册自己的样式,支持静音,非常灵活,文档丰富,并且更多。

例子:

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

印刷品:

演示:

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

prints:

Demo:


回答 9

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

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'

回答 10

试试这个简单的代码

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

Try this simple code

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

回答 11

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

On Windows you can use module ‘win32console’ (available in some Python distributions) or module ‘ctypes’ (Python 2.5 and up) to access the Win32 API.

To see complete code that supports both ways, see the color console reporting code from Testoob.

ctypes example:

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)

回答 12

基于@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')

Stupidly simple based on @joeld’s answer

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)

Then just

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

回答 13

我已经将@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")

I have wrapped @joeld answer into a module with global functions that I can use anywhere in my code.

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

use as follows:

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

回答 14

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

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

色彩

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

#

For Windows you cannot print to console with colors unless you’re using the win32api.

For Linux it’s as simple as using print, with the escape sequences outlined here:

Colors

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

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

I ended up doing this, I felt it was cleanest:

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)

回答 17

使用https://pypi.python.org/pypi/lazyme 在@joeld答案上构建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可能无法在所有终端上使用,在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

屏幕截图:

Building on @joeld answer, using 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

Screenshot:


Some updates to the color_print with new formatters, e.g.:

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

Note: italic, fast blinking and strikethrough may not work on all terminals, doesn’t work on Mac / Ubuntu.

E.g.

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

Screenshot:


回答 18

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

在线尝试

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


回答 19

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

note how well the with keyword mixes with modifiers like these that need to be reset (using Python 3 and 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")

回答 20

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

另外,运行此命令,您将找到您的盒子:

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

You can use the Python implementation of the curses library: http://docs.python.org/library/curses.html

Also, run this and you’ll find your box:

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

回答 21

您可以使用CLINT:

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

从GitHub获取它

You could use CLINT:

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

Get it from GitHub.


回答 22

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

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

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

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

回答 23

我知道我迟到了。但是,我有一个名为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))

这给您:

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

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

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

I know that I am late. But, I have a library called ColorIt. It is super simple.

Here are some examples:

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.

You might want to try it out: https://github.com/CodeForeverAndEver/ColorIt

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

If you are using Windows, then here you go!

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

回答 25

如果您使用的是Django

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

快照:

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

您可以测试它是否已安装在您的计算机中:
$ python -c "import django; print django.VERSION"
要安装它,请检查:如何安装Django

试试看!!

If you are using Django

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

snapshot:

(I generally use colored output for debugging on runserver terminal so I added it.)

You can test if it is installed in your machine:
$ python -c "import django; print django.VERSION"
To install it check: How to install Django

Give it a Try!!


回答 26

这是一个诅咒的例子:

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)

Here’s a curses example:

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)

回答 27

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

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

回答 28

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:

asciimatics provides a portable support for building text UI and animations:

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


回答 29

另一个包装python 3打印功能的pypi模块:

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

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

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

输出“你好,世界!” 用蓝色和感叹号标记为红色和闪烁。

Yet another pypi module that wraps the python 3 print function:

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

It’s usable in python 2.x if you also from __future__ import print. Here is a python 2 example from the modules pypi page:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

Outputs “Hello, world!” with the words in blue and the exclamation mark bold red and blinking.


Rich-Rich是一个Python库,用于终端中的富文本和美观的格式设置

中文 readme·Lengua española readme·Deutsche readme·Läs på svenska·日本語 readme·한국어 readme

Rich是一个Python库,用于富有终端中的文本和美观的格式

这个Rich API使您可以轻松地向终端输出添加颜色和样式。Rich还可以呈现漂亮的表格、进度条、标记、语法突出显示的源代码、回溯等等–开箱即用

有关Rich的视频介绍,请参阅calmcode.io通过@fishnets88

看看什么people are saying about Rich

兼容性

Rich适用于Linux、OSX和Windows。真彩色/表情符号适用于新的Windows终端,经典终端仅限16色。Rich需要Python 3.6.1或更高版本

Rich与Jupyter notebooks无需额外配置

正在安装

随一起安装pip或您最喜欢的PyPI包管理器

pip install rich

运行以下命令在您的终端上测试Rich Output:

python -m rich

丰富多彩的印刷品

若要毫不费力地向应用程序添加丰富的输出,可以将rich print方法,该方法与内置Python函数具有相同的签名。试试这个:

from rich import print

print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())

丰富的REPL

Rich可以安装在Python REPL中,这样任何数据结构都会非常漂亮地打印和突出显示

>>> from rich import pretty
>>> pretty.install()

使用控制台

要更好地控制富终端内容,请导入并构造Console对象

from rich.console import Console

console = Console()

Console对象有一个print方法,该方法的接口有意与构建的print功能。下面是一个使用示例:

console.print("Hello", "World!")

如您所料,这将打印出来"Hello World!"去航站楼。请注意,与建筑不同的是print函数时,Rich将对文本进行自动换行以适应终端宽度

有几种方法可以将颜色和样式添加到输出中。您可以为整个输出设置样式,方法是将style关键字参数。下面是一个示例:

console.print("Hello", "World!", style="bold red")

输出将如下所示:

对于一次设置一行文本的样式来说,这是很好的。对于更细粒度的样式,Rich呈现了一个特殊的标记,该标记在语法上类似于bbcode下面是一个示例:

console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")

您可以使用Console对象以最小的工作量生成复杂的输出。请参阅Console API详细信息请参阅文档

丰富考察

里奇有一个inspect可以生成有关任何Python对象(如类、实例或构建)的报告的函数

>>> my_list = ["foo", "bar"]
>>> from rich import inspect
>>> inspect(my_list, methods=True)

请参阅inspect docs有关详细信息,请参阅

丰富的图书馆

RICH包含多个建筑可渲染对象您可以使用在CLI中创建优雅的输出,并帮助您调试代码

有关详细信息,请单击以下标题:

日志

Console对象有一个log()方法,该方法具有类似于print(),而且还呈现当前时间的列以及进行调用的文件和行。默认情况下,Rich将对Python结构和REPR字符串进行语法高亮显示。如果您记录一个集合(例如,词典或列表),Rich会漂亮地打印它,以便它可以放在可用的空间中。以下是其中一些功能的示例

from rich.console import Console
console = Console()

test_data = [
    {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
    {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
    {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
]

def test_log():
    enabled = False
    context = {
        "foo": "bar",
    }
    movies = ["Deadpool", "Rise of the Skywalker"]
    console.log("Hello from", console, "!")
    console.log(test_data, log_locals=True)


test_log()

以上将产生以下输出:

请注意log_locals参数,该参数输出一个包含调用log方法的局部变量的表

LOG方法可用于登录到终端,用于长时间运行的应用程序(如服务器),但也是非常好的调试辅助工具

日志记录处理程序

您还可以使用内置的Handler class对来自Python日志记录模块的输出进行格式化和着色。以下是输出的示例:

表情符号

要在控制台输出中插入表情符号,请将名称放在两个冒号之间。下面是一个示例:

>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
😃 🧛 💩 👍 🦝

请明智地使用此功能

表格

丰富的可以灵活地呈现tables使用Unicode方框字符。边框、样式、单元格对齐等有多种格式选项

上面的动画是用table_movie.py在Examples目录中

下面是一个更简单的表格示例:

from rich.console import Console
from rich.table import Table

console = Console()

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row(
    "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
)
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,000",
    "$393,151,347",
)
table.add_row(
    "Dec 15, 2017",
    "Star Wars Ep. VIII: The Last Jedi",
    "$262,000,000",
    "[bold]$1,332,539,889[/bold]",
)

console.print(table)

这将产生以下输出:

请注意,控制台标记的呈现方式与print()log()事实上,Rich可以呈现的任何内容都可能包含在标题/行中(甚至其他表)

这个Table类足够智能,可以调整列的大小以适应终端的可用宽度,并根据需要对文本进行换行。下面是相同的示例,端子比上表小:

进度条

丰富的可以呈现多个无闪烁progress用于跟踪长期运行任务的条形图

对于基本用法,将任何序列包装在track函数并迭代结果。下面是一个示例:

from rich.progress import track

for step in track(range(100)):
    do_step(step)

添加多个进度条并不难。以下是文档中的一个示例:

这些列可以配置为显示您想要的任何详细信息。内置列包括完成百分比、文件大小、文件速度和剩余时间。下面是另一个示例,显示正在进行的下载:

要亲自尝试此功能,请参见examples/downloader.py它可以在显示进度的同时同时下载多个URL

状态

对于很难计算进度的情况,可以使用status方法,该方法将显示“微调器”动画和消息。动画不会阻止您正常使用控制台。下面是一个示例:

from time import sleep
from rich.console import Console

console = Console()
tasks = [f"task {n}" for n in range(1, 11)]

with console.status("[bold green]Working on tasks...") as status:
    while tasks:
        task = tasks.pop(0)
        sleep(1)
        console.log(f"{task} complete")

这将在终端中生成以下输出

微调器动画借用自cli-spinners您可以通过指定spinner参数。运行以下命令以查看可用值:

python -m rich.spinner

上面的命令在终端中生成以下输出:

Rich可以呈现一个tree带着指引线。树是显示文件结构或任何其他分层数据的理想选择

树的标签可以是简单的文本,也可以是Rich可以呈现的任何其他内容。运行以下命令进行演示:

python -m rich.tree

这将生成以下输出:

请参阅tree.py显示任何目录的树视图的脚本示例,类似于Linuxtree命令

Rich可以整齐地呈现内容columns具有相等或最佳宽度的。下面是(MacOS/Linux)的一个非常基本的克隆ls按列显示目录列表的命令:

import os
import sys

from rich import print
from rich.columns import Columns

directory = os.listdir(sys.argv[1])
print(Columns(directory))

下面的屏幕截图是columns example它以列的形式显示从API拉取的数据:

降价

Rich可以渲染markdown并且合理地将格式转换到终端

若要呈现标记,请将Markdown类,并使用包含标记代码的字符串构造它。然后将其打印到控制台。下面是一个示例:

from rich.console import Console
from rich.markdown import Markdown

console = Console()
with open("README.md") as readme:
    markdown = Markdown(readme.read())
console.print(markdown)

这将产生类似以下内容的输出:

语法突出显示

Rich使用pygments要实施的库syntax highlighting用法类似于呈现标记;构造Syntax对象,并将其打印到控制台。下面是一个示例:

from rich.console import Console
from rich.syntax import Syntax

my_code = '''
def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
    """Iterate and generate a tuple with a flag for first and last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    first = True
    for value in iter_values:
        yield first, False, previous_value
        first = False
        previous_value = value
    yield first, True, previous_value
'''
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
console = Console()
console.print(syntax)

这将产生以下输出:

跟踪回溯

Rich可以渲染beautiful tracebacks它们比标准Python回溯更容易阅读和显示更多代码。您可以将Rich设置为默认的回溯处理程序,这样所有未捕获的异常都将由Rich呈现

下面是它在OSX上的样子(与Linux类似):

所有丰富渲染器都使用Console Protocol,您还可以使用它来实现您自己的富内容

为企业发财致富

作为Tidelift订阅的一部分提供

Rich和数千个其他软件包的维护者正在与Tidelift合作,为您用来构建应用程序的开源软件包提供商业支持和维护。节省时间、降低风险并提高代码的健全性,同时付钱给您所使用的包的维护者。Learn more.

使用Rich的项目

以下是一些使用Rich的项目: