Thursday, July 26, 2012

python: download url to file with progress bar

This is an alternative answer for a question on stackoverflow:

I modified the answer a bit, using .format instead of % string formatting and sys.stdout.write(), and posted it on gist github:

# Improve
# (using .format() instead of % string formatting)

import sys
import urllib2

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta =
file_size = int(meta.getheaders("Content-Length")[0])
print("Downloading: {0} Bytes: {1}".format(url, file_size))

file_size_dl = 0
block_sz = 8192
while True:
    buffer =
    if not buffer:

    file_size_dl += len(buffer)
    p = float(file_size_dl) / file_size
    status = r"{0}  [{1:.2%}]".format(file_size_dl, p)
    status = status + chr(8)*(len(status)+1)


I'm using this solution for the kernel mainline ppa downloader:


Anonymous said...

I tries this but for some reason it takes an enormous amount of time to download. Is there a way to make it download faster?

Savvas Radevic said...

Nope, sorry. It's just a progress bar script, to show the percentage % you got of the file you're downloading.

Anonymous said...

Can you please explain the code?

Anonymous said...

Increasing the block_sz variable will increase the download speed.