Skip to content

Instantly share code, notes, and snippets.

@planetceres
Last active March 22, 2020 17:44
Show Gist options
  • Save planetceres/f3036baaa2e070d82e210149633b6bee to your computer and use it in GitHub Desktop.
Save planetceres/f3036baaa2e070d82e210149633b6bee to your computer and use it in GitHub Desktop.
Progress Bar with no Dependencies
# -*- coding: utf-8 -*-
#!/usr/bin/python
import sys
from termcolor import colored
# Print iterations progress
def color_select(iteration):
color = "cyan"
if iteration < total/4:
color = "red"
elif iteration < total/2:
color = "yellow"
elif iteration < total/(4.0/3):
color = "cyan"
else:
color = "green"
return color
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
bar_length - Optional : character length of bar (Int)
"""
str_format = "{0:." + str(decimals) + "f}"
percents = colored(str_format.format(100 * (iteration / float(total))), color_select(iteration))
filled_length = int(round(bar_length * iteration / float(total)))
bar = colored('█' * filled_length + '-' * (bar_length - filled_length), color_select(iteration))
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()

Python Progress Bar

Usage

refs:

import time

# A List of Items
item_list = list(range(0, 57))

# Initial call to print 0% progress
iter = 0
progress_len = len(item_list)
print_progress(0, progress_len, prefix='Progress:', suffix='Complete', bar_length=50)
for i, item in enumerate(items):
    # Do stuff...
    time.sleep(0.1)
    # Update Progress Bar
    iter += 1
    print_progress(iter, progress_len, prefix='Progress:', suffix='Complete', bar_length=50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment