1

I'm writing a script that has to download several files from the www. To make it more expressive I've just added a download hook to calculate the downloading percentage of the file that has being downloaded. Printing it out on the terminal produces a lot of output because I rewrite the same line each time the percentage counter is incremented, example:

1% - Downloading test.jpg
2% - Downloading test.jpg
... and so on

I'd like to obtain something like many bash scripts or programs (such as "apt-get" from ubuntu): refresh the line containing the percentage without have to write several times the same line containing the the updated percentage.

How can I do that? Thanks.

[edit] I'm using Python3.2 to develop the file downloader.

easwee
  • 15,757
  • 24
  • 60
  • 83
Ale A
  • 349
  • 5
  • 16

2 Answers2

2

You need curses:

http://docs.python.org/howto/curses.html

infrared
  • 3,566
  • 2
  • 25
  • 37
2

Use \r (carriage return) and write directly to the terminal with sys.stdout.write:

import time
import sys
for i in range(101):
    sys.stdout.write('%3d%%\r' % i)
    time.sleep(.1)

Or a little more Python 3-ish:

import time
for i in range(101):
    print('{:3}%'.format(i),end='\r')
    time.sleep(.1)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251