I can help you create a clean progress bar with a two-line display! Here's a solution using the tqdm library, which is excellent for progress bars:
from tqdm import tqdm
import time
import sys
class DualProgressBar:
def __init__(self, total, desc="Progress"):
self.pbar = tqdm(total=total, desc=desc, position=0, leave=True)
self.current_action = ""
def update(self, n=1, action=""):
self.pbar.update(n)
self.current_action = action
# Clear the line below the progress bar and print the action
tqdm.write(f"\r{' ' * 80}\r{action}", end='', file=sys.stdout)
def close(self):
self.pbar.close()
print() # Move to next line after completion
# Example usage
def demo():
tasks = [
("Downloading files", 3),
("Processing data", 2),
("Analyzing results", 4),
("Generating report", 1)
]
total_steps = sum(steps for _, steps in tasks)
progress = DualProgressBar(total=total_steps, desc="Overall Progress")
for task_name, steps in tasks:
for i in range(steps):
progress.update(1, f"Current: {task_name} ({i+1}/{steps})")
time.sleep(0.5) # Simulate work
progress.close()
if __name__ == "__main__":
demo()
If you want more control over the display or prefer not to use external libraries, here's a pure Python implementation:
import sys
import time
class ProgressBar:
def __init__(self, total, width=50):
self.total = total
self.width = width
self.current = 0
def update(self, action=""):
self.current += 1
percent = self.current / self.total
filled = int(self.width * percent)
# Move cursor up 2 lines and clear
sys.stdout.write('\033[2A\033[K')
# Draw progress bar
bar = '█' * filled + '░' * (self.width - filled)
sys.stdout.write(f'Progress: [{bar}] {percent*100:.1f}%\n')
# Write current action
sys.stdout.write(f'Current: {action}\033[K\n')
sys.stdout.flush()
def start(self):
# Initial empty lines for the display
print('\n')
# Example usage
def demo():
tasks = ["Initializing", "Loading data", "Processing", "Analyzing", "Finalizing"]
pb = ProgressBar(total=len(tasks))
pb.start()
for i, task in enumerate(tasks):
pb.update(f"{task}...")
time.sleep(1) # Simulate work
print("Complete!")
if __name__ == "__main__":
demo()
The first solution using tqdm is more robust and handles edge cases better, while the second gives you full control over the appearance. Both will give you a clean two-line display that updates in place without cluttering your terminal.
Which approach would you prefer, or would you like me to modify either of these to better fit your specific needs?