【问题标题】:Check for `urllib.urlretrieve(url, file_name)` Completion Status检查 `urllib.urlretrieve(url, file_name)` 完成状态
【发布时间】:2012-07-21 19:01:29
【问题描述】:

在允许我的程序前进到下一条语句之前,如何检查urllib.urlretrieve(url, file_name) 是否已完成?

以如下代码sn-p为例:

import traceback
import sys
import Image
from urllib import urlretrieve

try:
        print "Downloading gif....."
        urlretrieve(imgUrl, "tides.gif")
        # Allow time for image to download/save:
        time.sleep(5)
        print "Gif Downloaded."
    except:
        print "Failed to Download new GIF"
        raw_input('Press Enter to exit...')
        sys.exit()

    try:
        print "Converting GIF to JPG...."
        Image.open("tides.gif").convert('RGB').save("tides.jpg")
        print "Image Converted"
    except Exception, e:
        print "Conversion FAIL:", sys.exc_info()[0]
        traceback.print_exc()
        pass

当通过urlretrieve(imgUrl, "tides.gif") 下载'tides.gif' 的时间超过time.sleep(seconds) 导致文件为空或不完整时,Image.open("tides.gif") 会引发IOError(由于潮汐.gif 文件的大小0 KB)。

如何查看urlretrieve(imgUrl, "tides.gif")的状态,让我的程序只有在语句成功完成后才能前进?

【问题讨论】:

    标签: python urllib


    【解决方案1】:

    Requests 比 urllib 更好,但您应该能够这样做以同步下载文件:

    import urllib
    f = urllib.urlopen(imgUrl)
    with open("tides.gif", "wb") as imgFile:
        imgFile.write(f.read())
    # you won't get to this print until you've downloaded
    # all of the image at imgUrl or an exception is raised
    print "Got it!"
    

    这样做的缺点是它需要在内存中缓冲整个文件,因此如果您一次下载大量图像,您最终可能会使用大量内存。这不太可能,但仍然值得了解。

    【讨论】:

      【解决方案2】:

      我会使用来自http://docs.python-requests.org/en/latest/index.html 的python 请求,而不是普通的urllib2。 requests 默认情况下是同步的,因此如果不先获取图像,它就不会进入下一行代码。

      【讨论】:

      • requests 内部也有异步模型,但你需要geventgreenlet
      【解决方案3】:

      我在这里发现了一个类似的问题: Why is "raise IOError("cannot identify image file")"showing up only part of the time?

      更具体地说,请查看问题的答案。用户指向其他几个线程,这些线程准确地解释了如何以多种方式解决问题。您可能感兴趣的第一个包括进度条显示。

      【讨论】:

        【解决方案4】:

        所选答案不适用于大文件。这是正确的解决方案:

        import sys
        import time
        import urllib
        
        
        def reporthook(count, block_size, total_size):
            if int(count * block_size * 100 / total_size) == 100:
                print 'Download completed!'
        
        def save(url, filename):
            urllib.urlretrieve(url, filename, reporthook)
        

        【讨论】:

          【解决方案5】:

          你可以试试下面这个:

          import time
          
          # ----------------------------------------------------
          # Wait until the end of the download
          # ----------------------------------------------------
          
          valid=0
          while valid==0:
              try:
                  with open("tides.gif"):valid=1
              except IOError:
                  time.sleep(1)
          
          print "Got it !"
          
          # ----------------------------------------------------
          # //////////////////////////////////////////////////
          # ----------------------------------------------------
          

          【讨论】:

            猜你喜欢
            • 2019-08-06
            • 1970-01-01
            • 1970-01-01
            • 2017-09-03
            • 2014-01-18
            • 1970-01-01
            • 2020-10-20
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多