Skip to content

Instantly share code, notes, and snippets.

@fladd
Last active October 19, 2021 10:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fladd/36c422f1c0e9bf02f41f9fad19609d06 to your computer and use it in GitHub Desktop.
Save fladd/36c422f1c0e9bf02f41f9fad19609d06 to your computer and use it in GitHub Desktop.
Show the progress of a process with a simple text-based progress bar

show_progress

Show the progress of a process with a simple text-based progress bar

Code

def show_progress(progress, info="", length=40, symbols="[= ]", decimals=1):
    """Show the progress of a process with a simple text-based progress bar.

    Parameters
    ----------
    progress : (numeric, numeric)
        the current progress to be shown (count, total)
    info : str, optional
        the additional custom info displayed on the right (default="")
    length : int, optional
        the length of the progress bar displayed in the middle (default=40)
    symbols : (chr, chr, chr, chr), optional
        the symbols used to draw the progress bar (default="[= ]")
    decimals : int, optional
        the decimal places of the percantage displayed on the left (default=1)

    """

    percent = progress[0] / progress[1] * 100
    rjust = 3 + (decimals > 0) + decimals
    percentage = f"{percent:{rjust}.{decimals}f}%"
    filled_length = int(round(length * progress[0] / float(progress[1])))
    bar = f"{symbols[0]}{symbols[1] * filled_length}" \
          f"{symbols[2] * (length - filled_length)}{symbols[3]}"
    print(f"\033[K\r{percentage} {bar}{' ' + info if info else ''}", end="")
    if progress[0] == progress[1]:
        print("")

Example usage

import time


print("Default:")
for x in range(10000):
    time.sleep(0.0001)
    show_progress([x + 1, 10000])

print("Customize info:")
for x in range(10000):
    time.sleep(0.0001)
    show_progress([x + 1, 10000], info=f"({x + 1}/10000)")

print("Customize length:")
for x in range(10000):
    time.sleep(0.0001)
    show_progress([x + 1, 10000], info=f"({x + 1}/10000)", length=56)

print("Customize symbols:")
for x in range(10000):
    time.sleep(0.0001)
    show_progress([x + 1, 10000], info=f"({x + 1}/10000)", length=56,
                  symbols="|#-|")

print("Customize decimals:")
for x in range(10000):
    time.sleep(0.0001)
    show_progress([x + 1, 10000], info=f"({x + 1}/10000)", length=56,
                  symbols="|#-|", decimals=2)

show_progress

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