rich-terminal-output
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRich Terminal Output Skill
Rich终端输出技能
When to Activate
适用场景
Activate this skill when:
- Building CLI applications
- Displaying structured data (tables)
- Showing progress for long operations
- Creating error/status panels
- Pretty-printing objects for debugging
- Enhancing logging output
以下场景可使用本技能:
- 构建CLI应用
- 展示结构化数据(如表格)
- 显示长时操作的进度
- 创建错误/状态面板
- 格式化打印对象用于调试
- 增强日志输出效果
Installation
安装步骤
bash
uv add richbash
uv add richQuick test
快速测试
python -c "from rich import print; print('[bold green]Rich working![/]')"
undefinedpython -c "from rich import print; print('[bold green]Rich working![/]')"
undefinedCore Concepts
核心概念
Console Object
Console对象
python
from rich.console import Console
console = Console()python
from rich.console import Console
console = Console()Basic output
基础输出
console.print("Hello, World!")
console.print("Hello, World!")
Styled output
带样式的输出
console.print("[bold red]Error:[/] Something went wrong")
console.print("[green]Success![/] Operation completed")
undefinedconsole.print("[bold red]Error:[/] Something went wrong")
console.print("[green]Success![/] Operation completed")
undefinedMarkup Syntax
标记语法
python
"[bold]Bold[/]"
"[italic]Italic[/]"
"[red]Red text[/]"
"[blue on white]Blue on white background[/]"
"[bold red]Combined styles[/]"
"[link=https://example.com]Click here[/]"python
"[bold]Bold[/]"
"[italic]Italic[/]"
"[red]Red text[/]"
"[blue on white]Blue on white background[/]"
"[bold red]Combined styles[/]"
"[link=https://example.com]Click here[/]"Drop-in Print Replacement
替代原生Print函数
python
from rich import print
print("[bold cyan]Styled text[/]")
print({"key": "value"}) # Auto-pretty-printspython
from rich import print
print("[bold cyan]Styled text[/]")
print({"key": "value"}) # 自动格式化打印Tables
表格
python
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(title="User List")
table.add_column("ID", style="cyan", justify="right")
table.add_column("Name", style="magenta")
table.add_column("Email", style="green")
table.add_column("Status", justify="center")
table.add_row("1", "Alice", "alice@example.com", "✓ Active")
table.add_row("2", "Bob", "bob@example.com", "✓ Active")
table.add_row("3", "Charlie", "charlie@example.com", "✗ Inactive")
console.print(table)python
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(title="User List")
table.add_column("ID", style="cyan", justify="right")
table.add_column("Name", style="magenta")
table.add_column("Email", style="green")
table.add_column("Status", justify="center")
table.add_row("1", "Alice", "alice@example.com", "✓ Active")
table.add_row("2", "Bob", "bob@example.com", "✓ Active")
table.add_row("3", "Charlie", "charlie@example.com", "✗ Inactive")
console.print(table)Panels
面板
python
from rich.console import Console
from rich.panel import Panel
console = Console()python
from rich.console import Console
from rich.panel import Panel
console = Console()Simple panel
简单面板
console.print(Panel("Operation completed!"))
console.print(Panel("Operation completed!"))
Styled panel
带样式的面板
console.print(Panel(
"[green]All tests passed![/]\n\n"
"Total: 42 tests\n"
"Time: 3.2s",
title="Test Results",
border_style="green"
))
console.print(Panel(
"[green]All tests passed![/]\n\n"
"Total: 42 tests\n"
"Time: 3.2s",
title="Test Results",
border_style="green"
))
Error panel
错误面板
console.print(Panel(
"[red]Connection refused[/]\n\n"
"Host: localhost:5432",
title="[bold red]Error[/]",
border_style="red"
))
undefinedconsole.print(Panel(
"[red]Connection refused[/]\n\n"
"Host: localhost:5432",
title="[bold red]Error[/]",
border_style="red"
))
undefinedProgress Bars
进度条
Simple Progress
简单进度条
python
from rich.progress import track
import time
for item in track(range(100), description="Processing..."):
time.sleep(0.01)python
from rich.progress import track
import time
for item in track(range(100), description="Processing..."):
time.sleep(0.01)Multiple Tasks
多任务进度条
python
from rich.progress import Progress
with Progress() as progress:
task1 = progress.add_task("[red]Downloading...", total=100)
task2 = progress.add_task("[green]Processing...", total=100)
while not progress.finished:
progress.update(task1, advance=0.9)
progress.update(task2, advance=0.6)
time.sleep(0.02)python
from rich.progress import Progress
with Progress() as progress:
task1 = progress.add_task("[red]Downloading...", total=100)
task2 = progress.add_task("[green]Processing...", total=100)
while not progress.finished:
progress.update(task1, advance=0.9)
progress.update(task2, advance=0.6)
time.sleep(0.02)Syntax Highlighting
语法高亮
python
from rich.console import Console
from rich.syntax import Syntax
console = Console()
code = '''
def hello():
print("Hello, World!")
'''
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
console.print(syntax)python
from rich.console import Console
from rich.syntax import Syntax
console = Console()
code = '''
def hello():
print("Hello, World!")
'''
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
console.print(syntax)Tree Displays
树形展示
python
from rich.console import Console
from rich.tree import Tree
console = Console()
tree = Tree("[bold blue]MyProject/[/]")
src = tree.add("[bold]src/[/]")
src.add("main.py")
src.add("config.py")
tests = tree.add("[bold]tests/[/]")
tests.add("test_main.py")
console.print(tree)python
from rich.console import Console
from rich.tree import Tree
console = Console()
tree = Tree("[bold blue]MyProject/[/]")
src = tree.add("[bold]src/[/]")
src.add("main.py")
src.add("config.py")
tests = tree.add("[bold]tests/[/]")
tests.add("test_main.py")
console.print(tree)Logging Integration
日志集成
python
import logging
from rich.logging import RichHandler
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[RichHandler(rich_tracebacks=True)]
)
logger = logging.getLogger("myapp")
logger.info("Application started")
logger.error("Connection failed")python
import logging
from rich.logging import RichHandler
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[RichHandler(rich_tracebacks=True)]
)
logger = logging.getLogger("myapp")
logger.info("Application started")
logger.error("Connection failed")Pretty Tracebacks
美化回溯信息
python
from rich.traceback import installpython
from rich.traceback import installCall once at startup
在启动时调用一次
install(show_locals=True)
install(show_locals=True)
All exceptions now have beautiful tracebacks
此后所有异常都会显示美观的回溯信息
undefinedundefinedCommon Pitfalls
常见陷阱
Reuse Console Instance
复用Console实例
python
undefinedpython
undefined❌ Bad
❌ 错误做法
def show(msg):
Console().print(msg) # Creates new instance each time
def show(msg):
Console().print(msg) # 每次调用都创建新实例
✅ Good
✅ 正确做法
console = Console()
def show(msg):
console.print(msg)
undefinedconsole = Console()
def show(msg):
console.print(msg)
undefinedEscape User Input
转义用户输入
python
from rich.markup import escape
username = "user[admin]"python
from rich.markup import escape
username = "user[admin]"❌ Bad - brackets break markup
❌ 错误做法 - 括号会破坏标记语法
console.print(f"[blue]{username}[/]")
console.print(f"[blue]{username}[/]")
✅ Good
✅ 正确做法
console.print(f"[blue]{escape(username)}[/]")
undefinedconsole.print(f"[blue]{escape(username)}[/]")
undefinedHandle Non-TTY
处理非TTY环境
python
import sys
console = Console(force_terminal=sys.stdout.isatty())python
import sys
console = Console(force_terminal=sys.stdout.isatty())CLI Application Pattern
CLI应用模式
python
import click
from rich.console import Console
from rich.panel import Panel
console = Console()
@click.command()
@click.argument('filename')
def process(filename):
console.print(f"[bold]Processing:[/] {filename}")
with console.status("[bold green]Working..."):
result = do_work(filename)
if result.success:
console.print(Panel(
f"[green]Processed {result.count} items[/]",
title="Success"
))
else:
console.print(f"[red]Error:[/] {result.error}")python
import click
from rich.console import Console
from rich.panel import Panel
console = Console()
@click.command()
@click.argument('filename')
def process(filename):
console.print(f"[bold]Processing:[/] {filename}")
with console.status("[bold green]Working..."):
result = do_work(filename)
if result.success:
console.print(Panel(
f"[green]Processed {result.count} items[/]",
title="Success"
))
else:
console.print(f"[red]Error:[/] {result.error}")When NOT to Use Rich
不适用场景
- Non-interactive scripts (output piped)
- Server-side logging
- Performance-critical loops
- Minimal dependency requirements
- 非交互式脚本(输出被重定向)
- 服务器端日志
- 性能敏感的循环
- 对依赖包数量有严格要求的场景
Related Resources
相关资源
See for complete documentation including:
AgentUsage/rich_formatting.md- Advanced table customization
- Spinner and status displays
- Console recording
- Integration patterns
完整文档请查看,包括:
AgentUsage/rich_formatting.md- 高级表格自定义
- 加载动画和状态显示
- 终端录制
- 集成模式