views:

575

answers:

4

I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:

output:

Downloading File FooFile.txt [47%]

I'm trying to avoid something like this:

     Downloading File FooFile.txt [47%]
     Downloading File FooFile.txt [48%]
     Downloading File FooFile.txt [49%]

How should I go about doing this?


Duplicate: http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360

+2  A: 

Print the backspace character \b several times, and then overwrite the old number with the new number.

Zach Scrivena
interesting, I hadn't thought of doing it that way.
Chris Ballance
+4  A: 

Use a terminal-handling library like the curses module:

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

gimel
+9  A: 

You can also use the carriage return:

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
codelogic
Very common and simple solution. Note: if your line is longer than the width of your terminal, this gets ugly.
ephemient
I also had to add a call to sys.stdout.flush() so the cursor didn't bounce around
scottm
+2  A: 

I like the following:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,
RSabet