Reputation: 177
I am trying to implement a progress bar in my code. But it looks like for some reason the last element of previous progress status is not getting overridden. can someone explain why this is happening? Thanks.
threadLock = threading.Lock()
count = 0
def mail(email_no):
# Some code
with threadLock:
global count
count+=1
print('{} {}% completed. total sent={}'.format( chr(9608)*int((count/email_no)*100) ,((count/email_no)*100), count ), end ='\r' )
# server.quit()
email_no = 1008
for i in range(1, email_no+1):
t = Thread(target=mail, args=[email_no])
t.start()
It is giving me the following output:
████████████████████████████████████████████████████████████████████████████████ 100.0% completed. total sent=1008l sent=1007
why this total sent=1008l sent=1007
is coming instead of total sent = 1008 only?
Upvotes: 1
Views: 40
Reputation: 74655
The following assumes Python 3.
The issue is that that the final line is shorter than the line before it. This is caused that len("{}".format((1007/1008)*100))
is 17 and len("{}".format((1008/1008.)*100))
is 5. The difference is 10 which is also the length of the unwanted suffix l sent=1007
.
One way to fix this is to keep track of the length of the last line printed and then pad the line to that length with spaces. Another option is just to pad every line printed like line.ljust(os.get_terminal_size().columns)
.
import threading
from threading import Thread
threadLock = threading.Lock()
count = 0
last_line_length = 0
def mail(email_no):
# Some code
with threadLock:
global count, last_line_length
count+=1
line = '{} {}% completed. total sent={}'.format( chr(9608)*int((count/email_no)*100) ,((count/email_no)*100), count ).ljust(last_line_length)
print(line, end ='\r' )
last_line_length = len(line)
# server.quit()
email_no = 1008
for i in range(1, email_no+1):
t = Thread(target=mail, args=[email_no])
t.start()
Upvotes: 1