【发布时间】:2015-06-11 05:04:14
【问题描述】:
我有一个脚本可以检查当地天气并输出一个带有条件的字符串。
该脚本在我的 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 上都可以使用。
【问题讨论】:
-
您是否确认可以在 RPi 的命令行中运行
curl http://api.wunderground.com/api/%s/geolookup/conditions/q/PA/%s.json? -
我会尝试一些调试输出。一旦你将你的 url 变量设置为 print(url) 并把它放到浏览器中看看它是否有效。
-
从您的 URL 中删除“%”字符就可以了。自己检查:api.wunderground.com/api/s/geolookup/conditions/q/PA/s.json
-
@AlexIvanov:这些字符不是 URL 的一部分。它们是 Python 字符串模板的一部分并已填写。它们肯定不会导致名称查找无论如何失败。
-
是的。那是 Python 写的: url='api.wunderground.com/api/%s/geolookup/conditions/q/PA/%s.json' 我认为那是定义变量的用户。
标签: python json api raspberry-pi weather