Python 检查“urllib.urlretrieve(url,文件名)`完成状态
如何检查Python 检查“urllib.urlretrieve(url,文件名)`完成状态,python,urllib,Python,Urllib,如何检查urllib.urlretrieve(url,文件名)是否已完成,然后再允许我的程序前进到下一条语句 以以下代码段为例: import traceback import sys import Image from urllib import urlretrieve try: print "Downloading gif....." urlretrieve(imgUrl, "tides.gif") # Allow time for imag
urllib.urlretrieve(url,文件名)
是否已完成,然后再允许我的程序前进到下一条语句
以以下代码段为例:
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'的时间超过时间。睡眠(秒)
导致文件为空或不完整时,Image.open(“tides.gif”)
会引发IOError
(由于tides.gif文件大小为0 kB)
如何检查urlretrieve(imgUrl,“tides.gif”)的状态,使我的程序只有在语句成功完成后才能运行?我在这里发现了一个类似的问题:
更具体地说,请看问题的答案。用户指向另外两个线程,它们精确地解释了如何以多种方式解决问题。第一个,您可能会感兴趣,包括一个进度条显示。我将使用来自的python请求,而不是普通的urllib2。默认情况下,请求是同步的,因此如果不先获取映像,它将不会前进到下一行代码 请求比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!"
这样做的缺点是需要在内存中缓冲整个文件,因此如果一次下载大量图像,最终可能会使用大量ram。这不太可能,但仍然值得知道。所选答案不适用于大文件。以下是正确的解决方案:
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)
您可以在下面尝试:
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 !"
# ----------------------------------------------------
# //////////////////////////////////////////////////
# ----------------------------------------------------
请求中也有一个异步模型,但您需要gevent
和greenlet