2
import urllib2, sys

if len(sys.argv) !=3:
              print "Usage: download.py <link> <saveas>"
              sys.exit(1)

site = urllib2.urlopen(sys.argv[1])
meta = site.info()
print "Size: ", meta.getheaders("Content-Length")
f = open(sys.argv[2], 'wb')
f.write(site.read())
f.close()

I'm wondering how to display the file name and size before downloading and how to display the download progress of the file. Any help will be appreciated.

1
  • 2
    am I to assume the code you wrote doesn't work for showing the length? if not, what is the error you're getting? also: to know how long it will take, you obviously need to know the current speed of your connection; that could be difficult. Commented Nov 11, 2010 at 6:38

2 Answers 2

5

using urllib.urlretrieve


    import urllib, sys

    def progress_callback(blocks, block_size, total_size):
        #blocks->data downloaded so far (first argument of your callback)
        #block_size -> size of each block
        #total-size -> size of the file
        #implement code to calculate the percentage downloaded e.g
        print "downloaded %f%%" % blocks/float(total_size)

    if len(sys.argv) !=3:
        print "Usage: download.py  "
        sys.exit(1)

    site = urllib.urlopen(sys.argv[1])
    (file, headers) = urllib.urlretrieve(site, sys.argv[2], progress_callback)
    print headers

0
1

To display the filename: print f.name

To see all the cool things you can do with the file: dir(f)

I'm not sure I know what you mean when you say:

how to display how long it has before the file is finished downloading

If you want to display the time it took for the download, then you might want to take a look at the timeit module.

I this is not what you are looking for, then please update the question, so I can try to give you a better answer

2
  • Sorry for the inconvenience, what I ment to say was how can I track the progress of the download.
    – SourD
    Commented Nov 11, 2010 at 6:43
  • The answer to your updated question will strain the boundaries of my Python prowess, but let me give it a shot: I think you should start your download as one thread, downloading your file to a specific filename. Run a second thread that continually checks the size of the file being saved. This should give you a "downloaded so far: x KB", but I'm not sure if you can use this to output a "downloaded so far: x%" Commented Nov 11, 2010 at 23:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.