Skip to content

Instantly share code, notes, and snippets.

@HandsonMatheus
Created March 20, 2025 00:35
Show Gist options
  • Select an option

  • Save HandsonMatheus/d70ffd3913c951de393e925961032c7e to your computer and use it in GitHub Desktop.

Select an option

Save HandsonMatheus/d70ffd3913c951de393e925961032c7e to your computer and use it in GitHub Desktop.
import random, time
BAR = chr(9608) # Character 9608 is "█"
def main():
# simulate a download
print("Progress bar simulation")
bytes_downloaded = 0
download_size = 2048
while bytes_downloaded < download_size:
# "Download" a random amout of bytes:
bytes_downloaded += random.randint(0, 100)
# Get the progress bar string for this amount of progress:
bar_string = get_progress_bar(bytes_downloaded, download_size)
# don't print a newline at the end, and immediately flush the
# printed string to the screen:
print(bar_string, end='', flush=True)
time.sleep(0.2)
# print backspaces to move the text curso to the line's start:
print('\b' * len(bar_string), end='', flush=True)
def get_progress_bar(progress, total, barWidth=40):
""" Returns a string that represents a progress bar that has barWidth
bars and has progressed progress amount out of a total amount.
"""
progress_bar = '' # the progress bar will be a string value
progress_bar += '[' # create the left end of the progress bar
# make sure that the amount of progress is between 0 and total:
if progress > total:
progress = total
if progress < 0:
progress = 0
# calculate the number of bars to display:
number_of_bars = int((progress / total) * barWidth)
progress_bar += BAR * number_of_bars # add the progress bar
progress_bar += ' ' * (barWidth - number_of_bars) # add empty space
progress_bar += ']' # add the right end of the progress bar
# calculate the percentage complete:
percent_complete = round(progress / total * 100, 1)
# add the numbers:
progress_bar += ' ' + str(progress) + '/' + str(total)
return progress_bar
# if the program is run (instead of imported), run the game:
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment