Mini Project: Use a Library
Install and use the rich library to build colorful terminal output
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Using a third-party library
You installed rich earlier in this lesson. Now you will use it to build formatted terminal output. This is the workflow you will follow for every third-party package: install, import, use.
The rich library
rich makes terminal output look professional. Instead of plain print(), you can use:
Console— a replacement forprint()with color and style supportTable— displays data in formatted tablesPanel— wraps text in a bordered box
from rich.console import Console
from rich.table import Table
console = Console()
console.print("Hello!", style="bold green")Building a table
rich tables work in three steps:
- Create a
Tableobject with a title - Add columns with
add_column() - Add rows with
add_row()
table = Table(title="My Data")
table.add_column("Name", style="cyan")
table.add_column("Value", style="green")
table.add_row("Python", "3.12")
console.print(table)Your task
Build a project dependency viewer. Create a table that displays package information, then wrap it in styled output. This mimics what tools like pip list do, but with better formatting.
Instructions
Build a formatted dependency report using rich.
- Import
Consolefromrich.consoleandTablefromrich.table. - Create a variable named
consoleand assign itConsole(). - Create a variable named
packagesand assign it the list[("numpy", "1.26.4", "Math"), ("pypdf", "4.1.0", "PDF"), ("rich", "13.7.0", "Terminal")]. - Create a variable named
tableand assign itTable(title="Project Dependencies"). - Call
table.add_column("Package", style="cyan"). - Call
table.add_column("Version", style="green"). - Call
table.add_column("Purpose", style="yellow"). - Loop through
packageswith loop variablename, version, purpose. Inside the loop, calltable.add_row(name, version, purpose). - Call
console.print(table). - Call
console.print()withf"Total: {len(packages)} packages"andstyle="bold".
# Step 1: Import Console and Table from rich # Step 2: Create a Console instance # Step 3: Create the packages list # Step 4: Create a Table with title "Project Dependencies" # Step 5: Add "Package" column (cyan) # Step 6: Add "Version" column (green) # Step 7: Add "Purpose" column (yellow) # Step 8: Loop through packages and add each as a row # Step 9: Print the table # Step 10: Print the total count
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding