【问题标题】:Progress bar with downloading using urlopen使用 urlopen 下载的进度条
【发布时间】:2017-12-05 19:55:13
【问题描述】:

我的要求需要我从 http url 下载一个包并查看其进度。

我写了下面的代码

import subprocess
from urllib import urlopen


  class MyClass(object):
  '''
  classdocs
  '''

def url_to_download(self):
    url_for_download = "someurl"
    file = "somefilename"
    print "downloading with urllib"

    response = urlopen(url_for_download)
    CHUNK = 16 * 1024
    with open(file, 'wb') as f:
        while True:
            chunk = response.read(CHUNK)
            cmd = "ls -ltrh" + " " +file + " "+ "|"+ "awk '{print $5}'"
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            (output, err) = p.communicate()
            print "the download progress is" + " " + str(output)
            if not chunk:
                break
            f.write(chunk)


    if __name__ == "__main__":
     download =  MyClass()
      download.number_of_files()
      download.url_to_download()

如您所见,我基本上使用 linux 命令来查看下载进度。有什么方法可以对代码进行最小的更改,我可以获得下载的水平进度详细信息。 非常感谢提前

【问题讨论】:

    标签: python url urllib


    【解决方案1】:

    函数urlretrieve 有一个reporthook 回调——也就是说,你传递一个函数,urlretrieve 用3 个参数调用。

    至于进度条,您可以使用任何progress 模块作为 PyPI。例如,请参阅tqdm

    【讨论】:

      【解决方案2】:

      我建议使用现有的包,例如 progressbar2

      Docs

      安装:

      pip 安装进度条

      示例用法:

      import progressbar
      import urllib
      
      
      # Instantiate the progress bar
      bar = progressbar.ProgressBar()
      
      # Example URLS
      urls = ["http://www.stackoverflow.com","http://www.example.com"]
      
      # Iterate through urls and get the html
      for url in bar(urls):
          response = urllib.urlopen(url)
          html = response.read()
          #Do some additional processing here
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-27
        • 2014-03-13
        • 2019-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多