One of the most frustrating things when coding is running a long program without knowing its progress, whether it is executing normally or has frozen. At this point, a beautiful progress bar becomes particularly important. Today, I will share several super useful progress bar libraries in Python that not many people know about, making your programs look professional and cool instantly.
Not Just tqdm – The Glamorous Transformation of alive-progress
Most people think of tqdm when it comes to Python progress bars, but there is actually a cooler library called alive-progress. This library not only displays progress but also offers various styles.
from alive_progress import alive_bar
import time
# Basic usage
with alive_bar(100) as bar:
for i in range(100): time.sleep(0.02) # Simulate time-consuming operation bar() # Update progress
Looks plain? Hold on, this is just the appetizer. The real charm of alive-progress lies in its animation effects:
from alive_progress import alive_bar
import time
# Custom animation style
with alive_bar(50, bar='filling', spinner='dots_waves') as bar:
for i in range(50): time.sleep(0.1) bar()
# You can also do this
with alive_bar(30, bar='smooth', spinner='classic') as bar:
for item in range(30): time.sleep(0.05) bar.text = f’Processing task {item+1}…’ # Dynamic text bar()
⚠️ Tip: alive-progress has many options for the spinner parameter: dots, dots_waves, dots_recede, classic, etc., each with different animation effects. You can preview all styles using the command <span>python -m alive_progress.styles</span>.
The Progress Bar of the rich Library – The Pinnacle of Aesthetics
If alive-progress is practical, then the rich library’s progress bar is all about aesthetics. This library makes your terminal output look stunning.
from rich.progress import Progress, TextColumn, BarColumn, TimeRemainingColumn
import time
# Create a custom progress bar
with Progress(
TextColumn(“[bold blue]Task in Progress”, justify=”right”), BarColumn(bar_width=None), “[progress.percentage]{task.percentage:>3.1f}%”, “•”, TimeRemainingColumn(),
) as progress:
task = progress.add_task(“Downloading file”, total=100)
for i in range(100): time.sleep(0.02) progress.update(task, advance=1)
The power of rich lies in its ability to display multiple progress bars simultaneously:
from rich.progress import Progress
import time
import threading
def download_file(progress, task_id, file_name):
“””Simulate file download””” for i in range(100): time.sleep(0.01) progress.update(task_id, advance=1, description=f”Downloading {file_name}”)
with Progress() as progress:
Add Multiple Tasks
task1 = progress.add_task(“file1.zip”, total=100) task2 = progress.add_task(“file2.pdf”, total=100) task3 = progress.add_task(“file3.mp4”, total=100)
Concurrent Execution
threads = [ threading.Thread(target=download_file, args=(progress, task1, “file1.zip”)), threading.Thread(target=download_file, args=(progress, task2, “file2.pdf”)), threading.Thread(target=download_file, args=(progress, task3, “file3.mp4”)) ]
for thread in threads: thread.start() for thread in threads: thread.join()
The Time-Tested progressbar2
Although the name sounds plain, progressbar2 performs excellently in certain scenarios, especially when precise control over progress display is needed.
import progressbar
import time
# Custom progress bar widgets
widgets = [
‘Progress: ‘, progressbar.Percentage(), ‘ ‘, progressbar.Bar(marker=’█’, left='[‘, right=’]’), ‘ ‘, progressbar.ETA(), ‘ ‘, progressbar.FileTransferSpeed(),
]
# Create progress bar
bar = progressbar.ProgressBar(widgets=widgets, max_value=100)
for i in range(100):
time.sleep(0.02) bar.update(i)
bar.finish()
The strength of progressbar2 is its memory efficiency, which does not impose additional burdens when handling large datasets:
import progressbar
# Usage when processing large files
def process_large_file(filename):
with open(filename, ‘r’) as f: # First get the total number of lines total_lines = sum(1 for line in f) f.seek(0) # Reset file pointer
with progressbar.ProgressBar(max_value=total_lines) as bar:
for i, line in enumerate(f):
# Process each line of data
process_line(line)
bar.update(i)
def process_line(line):
Simulate Line Processing
pass
Advanced Techniques – Customizing Progress Bar Styles
Want to stand out? You can customize the appearance and behavior of the progress bar:
import sys
import time
class CustomProgressBar:
def init(self, total, width=50): self.total = total self.width = width self.current = 0
def update(self, step=1): self.current += step self.display()
def display(self): percent = self.current / self.total filled_width = int(self.width * percent)
# Custom progress bar character
bar = '█' * filled_width + '░' * (self.width - filled_width)
# Add color support (requires colorama library)
sys.stdout.write(f'\r\033[32m[{bar}]\033[0m {percent:.1%} ({self.current}/{self.total})')
sys.stdout.flush()
if self.current >= self.total:
print() # New line after completion
# Use custom progress bar
progress = CustomProgressBar(total=100)
for i in range(100):
time.sleep(0.02) progress.update()
Practical Application Scenarios
These progress bar tools are particularly useful in real projects. For example, when handling data scraping tasks:
import requests
from alive_progress import alive_bar
def crawl_websites(urls):
results = []
with alive_bar(len(urls), title=’Scraping Progress’) as bar: for url in urls: try: response = requests.get(url, timeout=5) results.append(response.status_code) bar.text = f’Scraping: {url[:30]}…’ except Exception as e: bar.text = f’Failed: {url[:30]}… Error: {str(e)[:20]}’ results.append(None) finally: bar()
return results
# Usage example
urls = ['https://www.python.org', 'https://github.com', 'https://stackoverflow.com']
status_codes = crawl_websites(urls)
⚠️ Tip: When using progress bars in production environments, be careful not to update the progress bar too frequently, as this may affect program performance. Typically, updating every 0.1 seconds is sufficient.
Progress bars are not just decorations; they let users know that the program is running normally, enhancing user experience. The choice of which progress bar library to use mainly depends on the requirements: for simple tasks, tqdm is sufficient; for multi-task displays, use rich; for memory efficiency, choose progressbar2; for visual effects, use alive-progress.
With these tools mastered, your Python programs will instantly become more professional. Users will no longer doubt whether the program has frozen when they see a black screen.