开发者

Downloading a file in Python

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],开发者_如何学C '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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜