0

I want to update a line of text, so that I don't have too many lines of output. Look at an installer program for an example:

Instead of...

Installation status: 1%

Installation status: 2%

Installation status: 3%

...

... I want the same line to update every time the percentage changes.

I already found a way to do so (well, it's actually tricking the user), but it is kind of bad, because all the lines from above disappear. I'm talking about importing 'os' and then doing 'os.system("clear")'.

Is there a better way of doing so?

BTW: I'm talking about a few hundred changes per second. The installer is just an example.

Reum12
  • 59
  • 6
  • 6
    Related: [Loading animation in python](http://stackoverflow.com/q/30200257/953482) or [Replace console output in python](http://stackoverflow.com/q/6169217/953482) or [Python Progress Bar](http://stackoverflow.com/q/3160699/953482) or [Output to the same line overwriting previous](http://stackoverflow.com/q/26584003/953482) – Kevin Aug 24 '15 at 16:34

3 Answers3

3

Use the appendage \r and then sys.stdout.flush()

To continue to use the installer example:

import sys
import time
for i in range(100):
    sys.stdout.write("\rInstallation Progress: %d percent" % i)
    time.sleep(.05)
    sys.stdout.flush()

Happy coding!

EDIT--I used % to represent percent completed. The result was an incomplete placeholder. My apologies!

Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
2

This has nothing to do with python, but with outputting to stdout: You can manipulate the position of the cursor using the backspace(\b) or the carriage return(\r) character. Depending on exactly what you are trying to achieve, you will need to use some combination of these. You can look at this as an example.

Community
  • 1
  • 1
deborah-digges
  • 1,165
  • 11
  • 19
1

You can have a nice animation if you want:

import sys
import time

barWidth = 50 # you can play with this
def updateProgressBar(value):
    line = '\r%s%%[%s]' % ( str(value).rjust(3), '-' * int ((float(value)/100) * barWidth))  
    print line,
    sys.stdout.flush()

for i in range(1,101):
    updateProgressBar(i)
    time.sleep(0.05) # do the job here

This will give you outputs of the following format:

100%[--------------------------------------------------]

PS: You can change print line, with print(line, end='') for Python 3.

Sait
  • 19,045
  • 18
  • 72
  • 99