A pure solution using the end
parameter of print()
:
The print()
statement allows you to specify what last chars
are printed at the end of the call. By default, end
is set to '\r\n'
which is a carriage return and newline. This moves the 'cursor' to the start of the next line which is what you would want in most cases.
However for a progress bar, you want to be able to print back over the bar so you can change the current position and percentage without the end result looking bad over multiple lines.
To do this, we need to set the end
parameter to just a carriage return: '\r'
. This will bring our current position back to the start of the line so we can re-print
over the progress bar.
As a demonstration of how this could work, I made this simple little code that will increase the progress bar by 1%
every 0.5
seconds. The key part of the code is the print
statement so this is the part that you will probably take away and put into your main script.
import time, math
bl = 50 #the length of the bar
for p in range(101):
chars = math.ceil(p * (bl/100))
print('▮' * chars + '▯' * (bl-chars), str(p) + '%', end='\r')
time.sleep(0.5)
(n.b. the chars used here are copied from your question ('▮, ▯') and for me they did not print to the console in which case you will need to replace them with other ones for example: '█' and '.')
This code does what you want and steadily increases the percentage, here is an example of how it would look when p = 42
:
▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯ 42%