【问题标题】:Downloading a file in Python在 Python 中下载文件
【发布时间】:2013-02-04 08:38:42
【问题描述】:
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()

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

【问题讨论】:

  • 我是否可以假设您编写的代码无法显示长度?如果没有,你得到的错误是什么?另外:要知道需要多长时间,您显然需要知道当前的连接速度;这可能很困难。

标签: python urllib2


【解决方案1】:

使用 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】:

    显示文件名:print f.name

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

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

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

    如果您想显示下载所用的时间,那么您可能需要查看timeit 模块。

    我这不是你要找的,那么请更新问题,以便我可以尝试给你一个更好的答案

    【讨论】:

    • 很抱歉给您带来不便,我想说的是如何跟踪下载进度。
    • 您更新后的问题的答案将限制我的 Python 能力,但让我试一试:我认为您应该以一个线程的形式开始下载,将文件下载到特定的文件名。运行第二个线程,不断检查正在保存的文件的大小。这应该给你一个“到目前为止下载:x KB”,但我不确定你是否可以使用它来输出“到目前为止下载:x%”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多