Created
August 24, 2019 10:14
-
-
Save shakeyourbunny/303b000168edc2705262ce40381034a3 to your computer and use it in GitHub Desktop.
python progressbar in text mode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little change, a little better...