1"""Progress Bar Simulation, by Al Sweigart al@inventwithpython.com
2A sample progress bar animation that can be used in other programs.
3This code is available at https://nostarch.com/big-book-small-python-programming
4Tags: tiny, module"""
5
6import random, time
7
8BAR = chr(9608) # Character 9608 is '█'
9
10def main():
11 # Simulate a download:
12 print('Progress Bar Simulation, by Al Sweigart')
13 bytesDownloaded = 0
14 downloadSize = 4096
15 while bytesDownloaded < downloadSize:
16 # "Download" a random amount of "bytes":
17 bytesDownloaded += random.randint(0, 100)
18
19 # Get the progress bar string for this amount of progress:
20 barStr = getProgressBar(bytesDownloaded, downloadSize)
21
22 # Don't print a newline at the end, and immediately flush the
23 # printed string to the screen:
24 print(barStr, end='', flush=True)
25
26 time.sleep(0.2) # Pause for a little bit:
27
28 # Print backspaces to move the text cursor to the line's start:
29 print('\b' * len(barStr), end='', flush=True)
30
31
32def getProgressBar(progress, total, barWidth=40):
33 """Returns a string that represents a progress bar that has barWidth
34 bars and has progressed progress amount out of a total amount."""
35
36 progressBar = '' # The progress bar will be a string value.
37 progressBar += '[' # Create the left end of the progress bar.
38
39 # Make sure that the amount of progress is between 0 and total:
40 if progress > total:
41 progress = total
42 if progress < 0:
43 progress = 0
44
45 # Calculate the number of "bars" to display:
46 numberOfBars = int((progress / total) * barWidth)
47
48 progressBar += BAR * numberOfBars # Add the progress bar.
49 progressBar += ' ' * (barWidth - numberOfBars) # Add empty space.
50 progressBar += ']' # Add the right end of the progress bar.
51
52 # Calculate the percentage complete:
53 percentComplete = round(progress / total * 100, 1)
54 progressBar += ' ' + str(percentComplete) + '%' # Add percentage.
55
56 # Add the numbers:
57 progressBar += ' ' + str(progress) + '/' + str(total)
58
59 return progressBar # Return the progress bar string.
60
61
62# If the program is run (instead of imported), run the game:
63if __name__ == '__main__':
64 main()