How to Create a Rich Console Progress Bar Mock in Python
This code uses Rich's Console and Progress API to build a simulated progress bar for a long-running task, updating progress and printing status messages.
pip install rich
Python code
28 linesimport time
from rich.console import Console
from rich.progress import Progress, BarColumn, TextColumn, PercentageColumn
console = Console()
def run_simulation():
console.print("[bold cyan]Starting simulated task...[/bold cyan]")
with Progress(
TextColumn("[bold blue]{task.description}[/bold blue]"),
BarColumn(bar_width=30),
PercentageColumn(),
console=console
) as progress:
task = progress.add_task("Processing items", total=100)
for i in range(100):
time.sleep(0.05)
progress.update(task, advance=1)
if i == 49:
console.print("[yellow]Halfway there![/yellow]")
console.print("[bold green]Task complete![/bold green]")
if __name__ == "__main__":
run_simulation()
Output
Starting simulated task...
[progress bar: ################################ ] 50%
Halfway there!
[progress bar: ############################################################] 100%
Task complete!
How it works
Rich's Progress context manager creates a live-updating progress bar that refreshes automatically. add_task registers a new task with a total count, and update advances its progress in a loop. Custom columns like TextColumn, BarColumn, and PercentageColumn control the display format. The console.print calls in the loop interleave text with the progress bar, appearing above it. When the with block exits, the bar is finalized to 100%.
Common mistakes
- Forgetting to call `update` in every iteration, causing the bar to stall.
- Using `total` as a count of steps instead of units, leading to premature completion.
- Nesting progress bars without different task IDs, which Rich will reject.
- Printing to console inside the loop without using Rich's print, which may break layout.
Variations
- Use `track` from rich.progress for a simple one-liner progress loop.
- Define a custom Column class to show elapsed time or custom metadata.
Real-world use cases
- Simulating a long-running data processing pipeline to test CLI output appearance without real work.
- Creating a visual demo of a progress bar during a conference talk or tutorial.
- Adding a placeholder progress indicator in a script while waiting for a real backend to be implemented.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.