Downloading a file in Python

試著忘記壹切 提交于 2020-01-11 10:59:13

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/4151841/downloading-a-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!