用Python下载文件 导入urllib2,sys 如果len(sys.argv)=三: 打印“用法:下载.py” 系统出口(1) site=urlib2.urlopen(sys.argv[1]) meta=site.info() 打印“大小:”,meta.getheaders(“内容长度”) f=打开(sys.argv[2],'wb') f、 写入(site.read()) f、 关闭()

用Python下载文件 导入urllib2,sys 如果len(sys.argv)=三: 打印“用法:下载.py” 系统出口(1) site=urlib2.urlopen(sys.argv[1]) meta=site.info() 打印“大小:”,meta.getheaders(“内容长度”) f=打开(sys.argv[2],'wb') f、 写入(site.read()) f、 关闭(),python,urllib2,Python,Urllib2,我想知道下载前如何显示文件名和大小,以及如何显示文件的下载进度。任何帮助都将不胜感激。要显示文件名:print f.name 要查看您可以对该文件执行的所有酷操作:dir(f) 我不知道你说的是什么意思: import urllib2, sys if len(sys.argv) !=3: print "Usage: download.py <link> <saveas>" sys.exit(1) site = u

我想知道下载前如何显示文件名和大小,以及如何显示文件的下载进度。任何帮助都将不胜感激。

要显示文件名:
print f.name

要查看您可以对该文件执行的所有酷操作:
dir(f)

我不知道你说的是什么意思:

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()
如果要显示下载所用的时间,则可能需要查看
timeit
模块


我知道这不是你想要的,那么请更新问题,这样我可以尝试使用urllib.urlretrieve给你一个更好的答案

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

我是否可以假设您编写的代码不能显示长度?如果没有,您会遇到什么错误?另外:要知道需要多长时间,你显然需要知道你当前的连接速度;这可能会很困难。很抱歉给您带来不便,我想说的是我如何跟踪下载进度。您更新的问题的答案将限制我的Python能力,但让我试一试:我认为您应该作为一个线程开始下载,将文件下载到特定的文件名。运行第二个线程,持续检查要保存的文件的大小。这应该会给你一个“下载到目前为止:x KB”,但我不确定你是否可以用它来输出“下载到目前为止:x%”

    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