【问题标题】:Why is "raise IOError("cannot identify image file")"showing up only part of the time?为什么“raise IOError("cannot identify image file")”只显示部分时间?
【发布时间】:2012-07-21 14:49:53
【问题描述】:

我写了一个小程序,从NOAA下载最新的每日潮汐图,在图片中添加一个包含潮汐信息的文本表格,然后将此图片设置为我的桌面壁纸。

from bs4 import BeautifulSoup
import Image, ImageDraw, ImageFont
from urllib import urlretrieve
import urllib2
import time
import ctypes
import sys
import os
import datetime
import traceback


def Fetch_tideGraph():
    # Fetch the Tides Graph .gif
    #
    # Fetch the Station Home Page
    try:
        url = 'http://tidesandcurrents.noaa.gov/noaatidepredictions/viewDailyPredictions.jsp?Stationid=8637689'
        page = urllib2.urlopen(url)
        soup = BeautifulSoup(page.read())

        # Find the Url to the tides graph
        ImgElement = str(soup.find_all('input', { "alt" : "Daily Tide Prediction graphical plot" }))
        soup = BeautifulSoup(ImgElement)
        tag = soup.input
        src = str(tag['src'])
        imgUrl = 'http://tidesandcurrents.noaa.gov/noaatidepredictions' + src.lstrip('.')
        print imgUrl
    except Exception, e:
        print "Failed to Load Webpage"
        traceback.print_exc()
        raw_input('Press Enter to exit...')
        sys.exit()

    # Download the tide graph
    try:
        print "Downloading gif....."
        urlretrieve(imgUrl, "C:\\Users\\Jack\\Documents\\Py Projects\\tides.gif")
        # Allow time for image to save:
        time.sleep(5)
        print "Gif Downloaded."
    except:
        print "Failed to Download new GIF"
        raw_input('Press Enter to exit...')
        sys.exit()

    # Convert gif to jpg
    try:
        print "Converting GIF to JPG...."
        Image.open("C:\\Users\\Jack\\Documents\\Py Projects\\tides.gif").convert('RGB').save("C:\\Users\\Jack\\Documents\\Py Projects\\tides.jpg")
        print "Image Converted"
    except Exception, e:
        print "Conversion FAIL:", sys.exc_info()[0]
        traceback.print_exc()
        pass

def update_wallpaper():
    # Change the Wallpaper
    imgPath = 'C:\\Users\\Jack\\Documents\\Py Projects\\tides.jpg'
    SPI_SETDESKWALLPAPER = 20
    try:
        print "Updating WallPaper..."
        ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, imgPath, 0)
        print "Wallpaper Updated"
    except:
        print "Wallpaper update FAIL"
        raw_input('Press Enter to exit...')

def todays_tide():
    # Print Table of Todays Tides
    # Open Tide Tables and Image File:
    try:
        info = open('C:\\Users\\Jack\\Documents\\Py Projects\\AnnualTides.txt', 'r')
        img = Image.open('C:\\Users\\Jack\\Documents\\Py Projects\\tides.jpg')
    except IOError:
        print "Tide table look-up failed."
        traceback.print_exc()
    # Load Font:
    f = ImageFont.load_default()
    draw = ImageDraw.Draw(img)
    # Lookup todays tides by matching date to table:
    now = datetime.datetime.now()
    date = now.strftime("%Y/%m/%d")
    tomorrow = now.strftime("%Y/%m/") + str(now.day+1)
    # Draw on image:
    y = 30
    head = '   Date    Day Time      Ft cm High/Low'
    draw.text((150, 20), head, (0,0,0), font=f)
    for line in info.readlines():
        if date in line or tomorrow in line:
            line = line.replace('\t', ' ')
            draw.text((150, y), line, (0,0,0), font=f)
            y += 10
    info.close()
    img.save("C:\\Users\\Jack\\Documents\\Py Projects\\tides.jpg")




##########################################

def main():
    try:
        Fetch_tideGraph()
        todays_tide()
        update_wallpaper()
        raw_input('Press Enter to exit...')
    except:
        print "Error in main()", sys.exc_info()[0]
        raw_input('Press Enter to exit...')

###########################################

if __name__ == "__main__":
    main()

代码虽然相当难看,但似乎运行良好,除了一个我似乎无法解决的小错误。大多数时候,当我运行程序时,一切都很顺利,但每运行几次,我都会得到以下输出:

>>> 
http://tidesandcurrents.noaa.gov/noaatidepredictions/serveimage?filename=images/8637689/21072012/855/8637689_2012-07-22.gif
Downloading gif.....
Gif Downloaded.
Converting GIF to JPG....
Conversion FAIL: <type 'exceptions.IOError'>
Traceback (most recent call last):
  File "C:\Users\Jack\Documents\Py Projects\Tides.py", line 54, in Fetch_tideGraph
    Image.open("C:\\Users\\Jack\\Documents\\Py Projects\\tides.gif").convert('RGB').save("C:\\Users\\Jack\\Documents\\Py Projects\\tides.jpg")
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1980, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file
Updating WallPaper...
Wallpaper Updated
Press Enter to exit...
>>> 

帮助我了解并纠正此错误。为什么它只在部分时间发生?

【问题讨论】:

  • 我们不知道。您当时的输入是什么样的?
  • @Ignacio Vazquez-Abrams 输入如下: 通过 Fetch_tideGraph() 函数从 NOAA 网站提取潮汐.gif 文件。我需要这个 JPG 格式的 GIF,以便我可以使用它。尝试通过以下方式将潮汐.gif 转换为潮汐.jpg 时程序失败: Image.open("C:\\Users\\Jack\\Documents\\Py Projects\\tides.gif").convert('RGB' ).save("C:\\Users\\Jack\\Documents\\Py Projects\\tides.jpg").我还需要提供哪些其他输入信息?
  • 这就是预期的输入。 实际输入是什么。
  • 'tides'gif' 存在但不包含或包含有限的数据。

标签: python debugging io


【解决方案1】:

IOError 表明您的 gif 文件不完整,因此无法识别为 PIL 的图像。最可能的问题是,您的下载完成所需的时间超过了您在 try: 块中允许下载 gif 文件的 5 秒。

您可以尝试其他几种获取 url 的方法,以确保在继续之前获得完整的文件。 This one有进度条,也可以试试herehere

【讨论】:

  • 果然,我的 gif 文件的下载时间超过 5 秒,导致 'tides.gif' 文件为空。如果我允许我的程序有更多时间通过“time.sleep(10)”获取 gif,它会提高我的成功率,但是问题仍然存在。如何让我的程序执行等待 gif 下载完成后再继续?
  • 三个选项从我的脑海中浮出水面:1) 深入urllib2 文档以找到阻塞的 url 获取(因此您的脚本将等到完成); 2) 显式捕获 IOError 并再次 sleep(),然后循环; 3) 使用另一个工具(curl 或 wget)来获取文件,然后继续。
猜你喜欢
  • 2014-07-24
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 2014-03-08
  • 2018-11-07
  • 2013-11-22
  • 1970-01-01
相关资源
最近更新 更多