I am writing a little application to download files over http (as, for example, described here).
I also want to include a little download progress indicator showing the percentage of the download progress.
Here is what I came up with:
sys.stdout.write(rem_file + "...") urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("%2d%%" % percent) sys.stdout.write("\b\b\b") sys.stdout.flush()
Output: MyFileName... 9%
Any other ideas or recommendations to do this?
One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?
EDIT:
Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:
global rem_file # global variable to be used in dlProgress urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + rem_file + "...%d%%" % percent) sys.stdout.flush()
Output: MyFileName...9%
And the cursor shows up at the END of the line. Much better.
I used this code:
Thats how I did this could help you: https://github.com/mouuff/MouDownloader/blob/master/api/download.py
If you use the
curses
package, you have much greater control of the console. It also comes at a higher cost in code complexity and is probably unnecessary unless you are developing a large console-based app.For a simple solution, you can always put the spinning wheel at the end of the status messge (the sequence of characters
|, \, -, /
which actually looks nice under blinking cursor.For small files you may need to had this lines in order to avoid crazy percentages:
sys.stdout.write("\r%2d%%" % percent)
sys.stdout.flush()
Cheers
For what it's worth, here's the code I used to get it working:
Late to the party, as usual. Here's an implementation that supports reporting progress, like the core
urlretrieve
: