2

The print() function 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

This helps in adding milestones to a progress bar when necessary.

Gangula
  • 5,193
  • 4
  • 30
  • 59

1 Answers1

2

The trick here is to simply add a print() statement in the if condition before the second print(...) statement, without any arguments to reset the cursor back to its default behavior

#...
    if i==5:
        print() # this sends the cursor to the next line without changing anything in the current line
        print(str(i) + "loops done in " + timeTaken)

TIP

For curious folks, below are the resources on how to print progress-bar in terminal using python:

Gangula
  • 5,193
  • 4
  • 30
  • 59