Python: Reset the cursor to newline AFTER setting it to the beginning using `end="\r"`
Python print()
statement has a really useful argument called end
, which allows you to customize the text at the end of print and the placement of the cursor after print.
For Example you can use end='\r'
to print the text on same line multiple times, which is really useful to create progress-bar's and %complete statements.
But how do I reset the cursor back to a new-line after setting it to the beginning. For example, the following code:
import datetime
start_time = datetime.datetime.now()
sampleRange = range(10)
for i in range(10):
i=i+1
percentComplete = str(i/len(sampleRange)*100)
print(percentComplete + "% done", end="\r")
if i==5:
timeTaken = str(datetime.datetime.now() - start_time)
print(str(i) + "loops done in " + timeTaken)
results in an output:
5loops done in 0:00:00.001001
100.0% done
But the expected output is:
50% done
5loops done in 0:00:00.001001
100.0% done
NOTE: This helps in adding milestones to a progress bar when necessary.
from Recent Questions - Stack Overflow https://ift.tt/3zNpLss
https://ift.tt/eA8V8J
Comments
Post a Comment