I have requirement to show the current number of job completed without printing status of each job every time. for example, I have 100 job posting running in for loop
and before starting the for loop
I'll show print message job number "1" started, here is the sample code
i = 1
print(f "Job number {i} posted successfully")
for i in range(100):
i = 1
I want my print message Job number 1 posted successfully
, here 1
value of I
should auto increment after each job posting in for loop
. I don't want to put print
in for loop to print 100 message. Is there anyway it can be achieved in python?
CodePudding user response:
If you want a progress bar of sort, I recommend the tqdm
library, is my favorite.
Now for printing in the same line as before is simple, you need to print the \r
character.
Simple example
import time
for i in range(100):
print("\r","updating",i,end="")
time.sleep(1) #we put it to sleep so we can see the change gradually
This should print the that text in the same line, in your console so long that console support it, for example the IDLE console of python doesn't support it so this trick would not work there.
Important here is to also said to print that we don't want to go to the next line, which is the default, to change that is simple give the keyword only argument end
and set it to an empty string.
Edit Note: So long the text you're printing is the same or greater length than the previously printed one there will no problem, if it get shorted then there will be left over from the previous text that don't get overwritten and will messed up the msj, so see this just check this sample
for i in reversed(range(102)):
print("\r","updating",i,end="")
time.sleep(1) #we put it to sleep so we can see the change gradually
if that become a problem, simple adding some white space at the end equal to the difference will solve it.