Loading...
Loading...
A fast, extensible progress bar for Python and CLI. Instantly makes your loops show a smart progress meter with ETA, iterations per second, and customizable statistics. Minimal overhead. Use for monitoring long-running loops, simulations, data processing, ML training, file downloads, I/O operations, command-line tools, pandas operations, parallel tasks, and nested progress bars.
npx skill4agent add tondevrel/scientific-agent-skills tqdmfrom tqdm import tqdmtqdm.pandas()tqdm.notebooktqdm.contribfor item in tqdm(iterable):pip install tqdmfrom tqdm import tqdm
import time
# For Jupyter Notebooks specifically:
# from tqdm.notebook import tqdmimport time
from tqdm import tqdm
# Just wrap the range or list
for i in tqdm(range(1000)):
time.sleep(0.01) # Simulate worktqdm(range(10), desc="Processing")from tqdm.notebook import tqdm__len__totaltqdm.pandas().progress_apply()pbar = tqdm(...)withpbar.close()print()tqdm.write("message")ascii=Truefrom tqdm import tqdm
import time
# ❌ BAD: Mixing print() and tqdm (Corrupts the bar)
for i in tqdm(range(5)):
print(f"Doing step {i}") # Bar jumps to next line
time.sleep(0.1)
# ✅ GOOD: Use tqdm.write()
for i in tqdm(range(5)):
tqdm.write(f"Doing step {i}") # Bar stays at the bottom
time.sleep(0.1)
# ❌ BAD: Manual update without closing (Potential memory leak/UI hang)
pbar = tqdm(total=100)
for i in range(100):
pbar.update(1)
# Missing pbar.close()!
# ✅ GOOD: Use context manager
with tqdm(total=100) as pbar:
for i in range(100):
pbar.update(1)
# ❌ BAD: Wrapping an iterator with no length without 'total'
# tqdm(my_generator) # Shows count but no progress bar/ETApbar = tqdm(range(100))
for i in pbar:
# Update description dynamically
pbar.set_description(f"Processing Step {i}")
# Add custom stats (e.g., loss in ML)
pbar.set_postfix(loss=0.5/(i+1), accuracy=i/100)
time.sleep(0.05)# Useful for tracking bytes in file I/O or API calls
with tqdm(total=1024, unit='B', unit_scale=True, desc="Downloading") as pbar:
# Simulate chunked download
for chunk_size in [256, 128, 512, 128]:
time.sleep(0.5)
pbar.update(chunk_size)import pandas as pd
from tqdm import tqdm
# Initialize tqdm for pandas
tqdm.pandas(desc="Cleaning Data")
df = pd.DataFrame({'val': range(10000)})
# Use progress_apply instead of apply
result = df['val'].progress_apply(lambda x: x**2)# Perfect for Epochs vs Batches in deep learning
for epoch in tqdm(range(3), desc="Epochs"):
for batch in tqdm(range(10), desc="Batches", leave=False):
time.sleep(0.05)from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
def work(n):
time.sleep(0.1)
return n * 2
data = range(50)
with ThreadPoolExecutor() as executor:
# Use tqdm to monitor map results
results = list(tqdm(executor.map(work, data), total=len(data)))import os
def read_large_file(filepath):
"""Read a file while showing a progress bar based on bytes."""
file_size = os.path.getsize(filepath)
with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
# Process chunk
pbar.update(len(chunk))def run_simulation_suite(configs):
"""Run multiple simulations and log failures."""
results = []
with tqdm(configs, desc="Suite") as pbar:
for config in pbar:
try:
res = run_single_sim(config)
results.append(res)
except Exception as e:
tqdm.write(f"Error in config {config}: {e}")
pbar.set_postfix(success=len(results))
return resultsdef train_model(epochs, data_loader):
pbar = tqdm(range(epochs), desc="Training")
for epoch in pbar:
loss = compute_loss() # dummy
acc = compute_acc() # dummy
# Update the bar with current metrics
pbar.set_postfix(loss=f"{loss:.4f}", acc=f"{acc:.2%}")minintervalfor i in tqdm(range(1000000), mininterval=1.0):
passdisable=Trueimport os
# Check for environment variable
is_ci = os.environ.get('CI') == 'true'
for i in tqdm(range(100), disable=is_ci):
pass# ✅ Solution: Always use a 'with' statement or try-finally
# Or clear all instances if stuck:
from tqdm import tqdm
tqdm._instances.clear()# ✅ Solution: Use ASCII characters only
for i in tqdm(range(100), ascii=True):
pass# ✅ Solution: Specify the position explicitly
# Useful for manual multi-threading
pbar1 = tqdm(total=100, position=0)
pbar2 = tqdm(total=100, position=1)