Rich 简介#

使用 Rich 可以使你的命令行应用程序在视觉上更吸引人,并以更易读的方式呈现数据。通过美化打印和语法高亮数据结构,Rich 也可以成为调试的有用工具。

安装#

直接使用 pip 安装

pip install rich

如果需要提供 jupyter 集成,则需要

pip install "rich[jupyter]"

快速入门#

要迅速开始使用 Rich,最直接的方式是导入替代内置 print 函数的打印函数。这个替代函数接受与内置 print 相同的参数,并且可以直接作为替代品使用。以下是如何进行操作的示例:

from rich import print

通过这种方式,你可以立即开始使用 Rich 库,而无需对现有的代码进行太多修改。只需将 print 替换为 rich.print,即可在终端中看到带有颜色和样式的输出。

print("[italic red]Hello[/italic red] World!", locals())
Hello World!
{
    '__name__': '__main__',
    '__doc__': 'Automatically created module for IPython interactive environment',
    '__package__': None,
    '__loader__': None,
    '__spec__': None,
    '__builtin__': <module 'builtins' (built-in)>,
    '__builtins__': <module 'builtins' (built-in)>,
    '_ih': ['', 'from rich import print', 'print("[italic red]Hello[/italic red] World!", locals())'],
    '_oh': {},
    '_dh': [PosixPath('/home/runner/work/d2py/d2py/doc/topics/tools/tasks/rich')],
    'In': ['', 'from rich import print', 'print("[italic red]Hello[/italic red] World!", locals())'],
    'Out': {},
    'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 
0x7f4118550050>>,
    'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x7f4118521190>,
    'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x7f4118521190>,
    'open': <function open at 0x7f411e6894e0>,
    '_': '',
    '__': '',
    '___': '',
    '_i': 'from rich import print',
    '_ii': '',
    '_iii': '',
    '_i1': 'from rich import print',
    'print': <function print at 0x7f411855b380>,
    '_i2': 'print("[italic red]Hello[/italic red] World!", locals())'
}

如果你不想覆盖 Python 的内置 print 函数,你可以将 rich.print 导入为 rprint (例如):

from rich import print as rprint

在交互式命令行(REPL)中使用 Rich#

Rich 可以被安装到 Python 交互式命令行中,那样做以后,任何数据结构都可以被漂亮的打印出来,自带语法高亮。

from rich import pretty
pretty.install()
["Rich and pretty", True]

['Rich and pretty', True]

你也可以使用这个特性来尝试 Rich 的可渲染对象。下面是一个示例:

from rich.panel import Panel
Panel.fit("[bold yellow]Hi, I'm a Panel", border_style="red")
╭─────────────────╮
 Hi, I'm a Panel 
╰─────────────────╯

IPython 集成 rich#

Rich还包含 IPython 扩展,它可以执行相同的漂亮安装和漂亮的回溯。以下是如何加载它:

%load_ext rich

在 IPython 中运行上述代码将加载 Rich 的 IPython 扩展。这将启用 Rich 的漂亮打印功能,使得输出更加美观。

Rich Inspect#

Rich 有一个 inspect() 函数,它可以生成任何 Python 对象的报告。它是一个极好的调试辅助工具,也是 Rich 可以生成的输出的一个很好的例子。下面是一个简单的示例:

from rich import inspect

obj = {"name": "John", "age": 30, "city": "New York"}

inspect(obj)
╭──────────────────────────── <class 'dict'> ────────────────────────────╮
 dict() -> new empty dictionary                                         
 dict(mapping) -> new dictionary initialized from a mapping object's    
     (key, value) pairs                                                 
 dict(iterable) -> new dictionary initialized as if via:                
     d = {}                                                             
     for k, v in iterable:                                              
         d[k] = v                                                       
 dict(**kwargs) -> new dictionary initialized with the name=value pairs 
     in the keyword argument list.  For example:  dict(one=1, two=2)    
                                                                        
 ╭────────────────────────────────────────────────────────────────────╮ 
  {'name': 'John', 'age': 30, 'city': 'New York'}                     
 ╰────────────────────────────────────────────────────────────────────╯ 
                                                                        
 35 attribute(s) not shown. Run inspect(inspect) for options.           
╰────────────────────────────────────────────────────────────────────────╯

在这个例子中,我们首先从 rich 模块导入了 inspect 函数,然后创建了一个包含一些键值对的字典对象。接着,我们使用 inspect() 函数来生成这个对象的报告。这将以美观的方式显示对象的内容和结构。

from rich import inspect
from rich.color import Color
color = Color.parse("red")
inspect(color, methods=True)
╭────────────────────────────────────────── <class 'rich.color.Color'> ───────────────────────────────────────────╮
 Terminal color definition.                                                                                      
                                                                                                                 
 ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ 
  Color('red', ColorType.STANDARD, number=1)                                                                   
 ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ 
                                                                                                                 
        is_default = False                                                                                       
 is_system_defined = True                                                                                        
              name = 'red'                                                                                       
            number = 1                                                                                           
            system = ColorSystem.STANDARD                                                                        
           triplet = None                                                                                        
              type = ColorType.STANDARD                                                                          
             count = def count(value, /): Return number of occurrences of value.                                 
           default = def default() -> 'Color': Get a Color instance representing the default color.              
         downgrade = def downgrade(system: rich.color.ColorSystem) -> 'Color': Downgrade a color system to a     
                     system with fewer colors.                                                                   
         from_ansi = def from_ansi(number: int) -> 'Color': Create a Color number from it's 8-bit ansi number.   
          from_rgb = def from_rgb(red: float, green: float, blue: float) -> 'Color': Create a truecolor from     
                     three color components in the range(0->255).                                                
      from_triplet = def from_triplet(triplet: 'ColorTriplet') -> 'Color': Create a truecolor RGB color from a   
                     triplet of values.                                                                          
    get_ansi_codes = def get_ansi_codes(foreground: bool = True) -> Tuple[str, ...]: Get the ANSI escape codes   
                     for this color.                                                                             
     get_truecolor = def get_truecolor(theme: Optional[ForwardRef('TerminalTheme')] = None, foreground: bool =   
                     True) -> rich.color_triplet.ColorTriplet: Get an equivalent color triplet for this color.   
             index = def index(value, start=0, stop=9223372036854775807, /): Return first index of value.        
             parse = def parse(color: str) -> 'Color': Parse a color definition.                                 
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯