Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakeyourbunny/303b000168edc2705262ce40381034a3 to your computer and use it in GitHub Desktop.
Save shakeyourbunny/303b000168edc2705262ce40381034a3 to your computer and use it in GitHub Desktop.
python progressbar in text mode
# progress bar with autosizing in text mode, works in the standard Windows command line interface too
# based on https://stackoverflow.com/a/34325723
# alternative solution to https://gist.github.com/greenstick/b23e475d2bfdc3a82e34eaa1f6781ee4 without
# doing an subprocess (why even..?)
#
# modifications:
# - autosizing to console with, also works with Windows command line.
# - percent display has been made optional
#
import shutil
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', usepercent = True, decimals = 1, fill = '█'):
"""
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)
usepercent - Optoinal : display percentage (Bool)
decimals - Optional : positive number of decimals in percent complete (Int), ignored if usepercent = False
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
"""
# length is calculated by terminal width
twx, twy = shutil.get_terminal_size()
length = twx - 1 - len(prefix) - len(suffix) -4
if usepercent:
length = length - 6
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
# process percent
if usepercent:
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='', flush=True)
else:
print('\r%s |%s| %s' % (prefix, bar, suffix), end='', flush=True)
# Print New Line on Complete
if iteration == total:
print(flush=True)
@ezequias
Copy link

Sorry but it dows not work for me.

How do you call in the loop?

image

@ezequias
Copy link

A little change, a little better...

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment