Python:urllib2错误“名称或服务器未知”

帕特里克·库克(Patrick Cook)

我有一个检查当地天气并输出条件字符串的脚本。

该脚本可以在Mac上正常运行,但是当我通过SSH在Raspberry Pi上运行该脚本时,它将返回以下错误:

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。

更新

多亏了一些评论者,我发现问题是当我输入以下内容时:

curl api.wunderground.com

在RPi的命令行中,它返回can't resolve hostname虽然在我的Mac上工作正常。问题是什么?

另外,这一天前在我的Pi和Mac上都可以正常工作。

ny

问题是您的rasberry-pi无法解析域名http://api.wunderground.com可能有两个原因。

  1. 它未连接到互联网(直接wifi /以太网或共享连接)
  2. 它的DNS服务器未配置,因此它不知道与谁联系以将域名解析为IP地址

如果您确定您的RPi已连接到互联网,则可以通过ping google.com,然后从RPi ping 8.8.8.8(公共DNS服务器)来测试理论2。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章