snippetpythonrichTippending
Python rich library for beautiful terminal output
Viewed 0 times
richterminaltableprogresscolorcli
Problem
Terminal output from scripts and CLIs is plain and hard to read. Need formatted tables, progress bars, and colored output.
Solution
Use the rich library for beautiful terminal output:
from rich.console import Console
from rich.table import Table
from rich.progress import track
from rich import print as rprint
console = Console()
# Colored and styled output
console.print('[bold green]Success![/] Operation completed')
console.print('[red]Error:[/red] File not found', style='bold')
# Tables
table = Table(title='Users')
table.add_column('Name', style='cyan')
table.add_column('Role', style='green')
table.add_column('Active', justify='center')
table.add_row('Alice', 'Admin', 'Yes')
table.add_row('Bob', 'User', 'No')
console.print(table)
# Progress bar
for item in track(range(100), description='Processing...'):
do_work(item)
# Pretty print data structures
rprint({'name': 'Alice', 'roles': ['admin', 'user'], 'active': True})
# Logging with rich handler
import logging
from rich.logging import RichHandler
logging.basicConfig(handlers=[RichHandler()])
log = logging.getLogger('app')
log.info('Server started on port 3000')
# Tree view
from rich.tree import Tree
tree = Tree('project/')
tree.add('src/').add('index.ts')
console.print(tree)
from rich.console import Console
from rich.table import Table
from rich.progress import track
from rich import print as rprint
console = Console()
# Colored and styled output
console.print('[bold green]Success![/] Operation completed')
console.print('[red]Error:[/red] File not found', style='bold')
# Tables
table = Table(title='Users')
table.add_column('Name', style='cyan')
table.add_column('Role', style='green')
table.add_column('Active', justify='center')
table.add_row('Alice', 'Admin', 'Yes')
table.add_row('Bob', 'User', 'No')
console.print(table)
# Progress bar
for item in track(range(100), description='Processing...'):
do_work(item)
# Pretty print data structures
rprint({'name': 'Alice', 'roles': ['admin', 'user'], 'active': True})
# Logging with rich handler
import logging
from rich.logging import RichHandler
logging.basicConfig(handlers=[RichHandler()])
log = logging.getLogger('app')
log.info('Server started on port 3000')
# Tree view
from rich.tree import Tree
tree = Tree('project/')
tree.add('src/').add('index.ts')
console.print(tree)
Why
rich makes CLI tools professional with minimal effort. Tables, progress bars, and syntax highlighting out of the box.
Revisions (0)
No revisions yet.