I really should read the documentation of the Rich library in detail… I just found another gem: the rich.status
module, which provides a spinner and status message while a task is being processed. This visual feedback informs the user that the application is actively working on a task, contributing to a more engaging and informative user interaction.
Code Example
import asyncio
import random
from rich.console import Console
from rich.status import Status
async def simulated_task():
# Simulate a task that may raise an error
await asyncio.sleep(2)
if random.random() < 0.5: # 50% chance of error
raise ValueError("An error occurred")
await asyncio.sleep(2)
async def main():
encountered_error = False
console = Console()
with console.status("[bold cyan]Processing...") as status:
try:
await simulated_task()
status.update("[bold green]Success!")
except ValueError as error:
status.update(f"[bold red]{error}")
encountered_error = True
await asyncio.sleep(2) # Simulate additional processing
console.print(
"Task complete" if not encountered_error else "Task encountered an error"
)
if __name__ == "__main__":
asyncio.run(main())
Spinner Styles
To view all the predefined spinner style names along with their visual representation, run the following command in your terminal:
Make sure you have the Rich library installed in your virtual environment (python -m pip install rich
).