我有一個腳本,檢查當地的天氣,並輸出一個字符串的條件。Python:urllib2錯誤「名稱或服務器未知」
該腳本適用於我的Mac罰款,但是當我通過SSH對我的樹莓派運行它,它返回此錯誤:
urllib2.URLError: <urlopen error [Errno -2] Name or service not known>
這裏是腳本返回錯誤的部分:
import urllib2
import json
import fnmatch
key='xxxxxxxxxxxxxxxx'
url='http://api.wunderground.com/api/%s/geolookup/conditions/q/PA/%s.json' %(key, zipCode)
f=urllib2.urlopen(url)
json_string = f.read()
parsed_json=json.loads(json_string)
city=parsed_json['location']['city']
state=parsed_json['location']['state']
weather=parsed_json['current_observation']['weather']
temperature = parsed_json['current_observation']['temperature_string']
report=("The current weather in " + str(city) + " " + str(state) + " is " + str(weather.lower()) + " and " + str(temperature)).replace("F (","degrees fahrenheit or ").replace("C)","degrees celsius")
return report
,這裏是完整的錯誤:
File "/home/pi/Desktop/Programming/Python/WeatherAlarm.py", line 77, in <module>
opening()
File "/home/pi/Desktop/Programming/Python/WeatherAlarm.py", line 52, in opening
wait(alarmtime, platform, sound, zipCode)
File "/home/pi/Desktop/Programming/Python/WeatherAlarm.py", line 75, in wait
alarm(platform, sound, zipCode)
File "/home/pi/Desktop/Programming/Python/WeatherAlarm.py", line 58, in alarm
say=Wunder(zipCode)
File "/home/pi/Desktop/Programming/Python/WeatherAlarm.py", line 12, in Wunder
f=urllib2.urlopen(url)
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 401, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 419, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1211, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1181, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno -2] Name or service not known>
我爲我的天氣預報使用Wunderground的API。
UPDATE
我發現,由於一些評論,這個問題是,當我進入:
curl api.wunderground.com
在RPI的命令行,它返回can't resolve hostname
。雖然它在我的Mac上正常工作。問題是什麼?
此外,這是一天前在我的Pi和我的Mac上工作。
您是否驗證過可以從RPi上的命令行運行'curl http:// api.wunderground.com/api /%s/geolookup/conditions/q/PA /%s.json'? –
我會嘗試一些調試輸出..只要你讓你的url變量,打印(網址),並把它放在瀏覽器中,看看它是否工作。 – user1269942
從你的網址中刪除「%」字符,它會沒事的。請自行檢查:http://api.wunderground.com/api/s/geolookup/conditions/q/PA/s.json –