我找到并修改了一个简单的Python代码,使用openweather和json格式获取天气状况。但是我有个问题——如果城市名称错误,该如何提示用户?我的意思是,即使我传入一个不存在的城市,程序也总会返回结果(没有“空响应”之类的信息)。
请查看下面的代码以了解我所说的内容:
请查看下面的代码以了解我所说的内容:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2, json
city = "etre4t5r5e4re" # the city name is incorrent
url = "http://openweathermap.org/data/2.1/forecast/city?q="
url += city
try :
request = urllib2.Request(url)
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except urllib2.URLError, e:
info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except httplib.HTTPException, e:
info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except Exception:
info = wx.MessageBox(u"Error", u"Error", wx.OK | wx.ICON_ERROR)
weather = response.read()
if __name__ == '__main__':
print(weather) # it will show weather but thats not what I want for non-existing city!
http://openweathermap.org/data/2.1/forecast/city?q=etre4t5r5e4re
对我来说返回了Internal Server Error Undefined index: geonames_id
。 - Niclas Nilssoncity = str(raw_input("请输入您的城市:\n> "))
,但无论我输入什么,都会有一个答案 :/ - mazix