2015-06-11 41 views
0

我有一個腳本,檢查當地的天氣,並輸出一個字符串的條件。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上工作。

+2

您是否驗證過可以從RPi上的命令行運行'curl http:// api.wunderground.com/api /%s/geolookup/conditions/q/PA /%s.json'? –

+0

我會嘗試一些調試輸出..只要你讓你的url變量,打印(網址),並把它放在瀏覽器中,看看它是否工作。 – user1269942

+1

從你的網址中刪除「%」字符,它會沒事的。請自行檢查:http://api.wunderground.com/api/s/geolookup/conditions/q/PA/s.json –

回答

1

問題是您的rasberry-pi無法解析域名http://api.wunderground.com。這可能有兩個原因。

  1. 它沒有連接到互聯網(直接Wi-Fi /以太網或共享連接)
  2. 它的DNS服務器未配置,因此它不知道誰聯繫來解決域名轉換爲IP地址

如果你確定你的RPi連接到互聯網,我會通過Pinging google.com然後從你的RPi ping 8.8.8.8(公共DNS服務器)來測試理論2。

0

有時,您使用的是代理而不自知:

您應該檢查代理ENV變量:

$ env | grep -i proxy 
http_proxy=http://someip:1757  
https_proxy=https://someip:1757 

如果沒有代理服務器,請檢查你的.bashrc並刪除它們的定義。 (我的情況:這是從另一臺桌面.bashrc粘貼的不好的&)。

相關問題