You are not logged in.
I'm having a problem. menu.xml has the code "/gweather.py ASXX0001"
The current weather seems to be ok in Celsius and with the correct celsius number, but the forecast units have the correct units, but show the weather temperature as the ferenheit one
Offline
that is nice here is it with the black blue ob theme .
Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD
Offline
I'm having a problem. menu.xml has the code "/gweather.py ASXX0001"
The current weather seems to be ok in Celsius and with the correct celsius number, but the forecast units have the correct units, but show the weather temperature as the ferenheit one
oh, I thought that google's feed was not working.
Change
#Celsius
#elif name == "temp_c":
#print "<item label='Temperature " + attrs["data"] + " C' />"
#elif name == "low":
#print "<item label='Minimun " + attrs["data"] + " C' />"
#elif name == "high":
#print "<item label='Maximun " + attrs["data"] + " C' />"
#Fahrenheit
elif name == "temp_f":
print "<item label='Temperature " + attrs["data"] + " F' />"
elif name == "low":
print "<item label='Minimun " + attrs["data"] + " F' />"
elif name == "high":
print "<item label='Maximun " + attrs["data"] + " F' />"
to
#Celsius
elif name == "temp_c":
print "<item label='Temperature " + attrs["data"] + " C' />"
elif name == "low":
print "<item label='Minimun " + attrs["data"] + " C' />"
elif name == "high":
print "<item label='Maximun " + attrs["data"] + " C' />"
#Fahrenheit
#elif name == "temp_f":
#print "<item label='Temperature " + attrs["data"] + " F' />"
#elif name == "low":
#print "<item label='Minimun " + attrs["data"] + " F' />"
#elif name == "high":
#print "<item label='Maximun " + attrs["data"] + " F' />"
Maybe I should rewrite the google script in a more elegant way, like the yahoo script
Last edited by noalwin (2009-05-10 02:17:52)
Offline
Hi, i was just trying your script and noticed the following:
i live in Göttingen in Germany and since you just changes the spanish characters, the script would not work.
to replace the german "umlaute" you need the following line:
trans=maketrans("\xE4\xC4\xF6\xD6\xFC\xDC\xDF","aAoOuUs")
Furthermore, i have a problem with the forecast:
i still use f = urllib.urlopen("http://www.google.com/ig/api?weather="+sys.argv[1]), because google.de wouldnt work.
the CURRENT weather information in celsius is correct, but it seems like the forecast is wrong: the numbers written there are in F, while the unit displayed is C. i would like to have the forecast temperature in celsius.
Offline
Hi, i was just trying your script and noticed the following:
i live in Göttingen in Germany and since you just changes the spanish characters, the script would not work.
to replace the german "umlaute" you need the following line:trans=maketrans("\xE4\xC4\xF6\xD6\xFC\xDC\xDF","aAoOuUs")
Furthermore, i have a problem with the forecast:
i still use f = urllib.urlopen("http://www.google.com/ig/api?weather="+sys.argv[1]), because google.de wouldnt work.
the CURRENT weather information in celsius is correct, but it seems like the forecast is wrong: the numbers written there are in F, while the unit displayed is C. i would like to have the forecast temperature in celsius.
You can add "&hl=de" to the URL to solve the temperature issue
About the non-ascii characters, I think that I got what happened (openbox reads the pipemenus as utf-8 even if the locale is latin-1" and now non-latin characters should work properly
I ended rewriting the script to obtain one like the yahoo script
You can use it as "gweather.py city language"
The language is the value of the "hl" parameter when you search something in google
#!/usr/bin/python -o
# -*- coding: utf-8 -*-
from urllib import urlopen, quote
from xml.etree.cElementTree import parse
from datetime import datetime, timedelta
import os
from os.path import join
from sys import argv
try:
import cPickle as pickle
except ImportError:
import pickle
TRANSLATED_TEXT = {
'en': {
'current': 'Current conditions',
'weather': 'Weather',
'temp': 'Temperature',
'humidity': 'Humidity',
'wind': 'Wind',
'forecast': 'Forecast',
'mintemp': 'Minimun Temperature',
'maxtemp': 'Maximun Temperature'
},
'es': {
'current': u'Actualmente',
'weather': u'Tiempo',
'temp': u'Temperatura',
'humidity': u'Humedad',
'wind': u'Viento',
'forecast': u'Previsión',
'mintemp': u'Temperatura Mínima',
'maxtemp': u'Temperatura Máxima'
},
'fr': {
'current': u'Actuel',
'weather': u'Météo',
'temp': u'Température',
'humidity': u'Humidité',
'wind': u'Vent',
'forecast': u'Prévision',
'mintemp': u'Température minimale',
'maxtemp': u'Température maximale'
},
'de': {
'current': u'Aktuell',
'weather': u'Wetter',
'temp': u'Temperatur',
'humidity': u'Luftfeuchtigkeit',
'wind': u'Wind',
'forecast': u'Prognostizieren',
'mintemp': u'Minimale Temperatur',
'maxtemp': u'Höchste Temperatur'
}
}
if len(argv) != 3:
raise Exception('Usage: gweather.py city language.')
else:
city = argv[1]
lang = argv[2]
CACHE_HOURS = 1
WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s&oe=UTF-8'
def get_weather(city, lang):
url = WEATHER_URL % (quote(city), quote(lang))
data = parse(urlopen(url))
forecasts = []
for forecast in data.findall('weather/forecast_conditions'):
forecasts.append(
dict([(element.tag, element.get("data")) for element in forecast.getchildren()]))
return {
'forecast_information': dict([(element.tag, element.get("data")) for element in data.find('weather/forecast_information').getchildren()]),
'current_conditions': dict([(element.tag, element.get("data")) for element in data.find('weather/current_conditions').getchildren()]),
'forecasts': forecasts
}
def get_openbox_pipe_menu(lang, forecast_information, current_conditions, forecasts):
if lang == 'en-US':
lang = 'en'
tt = TRANSLATED_TEXT[lang]
temp_var, temp_unit = ("temp_c", u"\u00b0C") if forecast_information['unit_system'] == "SI" else ("temp_f", "F")
output = '<openbox_pipe_menu>'
output += '\n<separator label="%s (%s)" />' % (weather['forecast_information']['city'],forecast_information['forecast_date'])
output += '\n<separator label="%s" />' % tt['current']
output += '<item label="%s: %s" />' % (tt['weather'], current_conditions['condition'])
output += '<item label="%s: %s %s" />' % (tt['temp'], current_conditions[temp_var], temp_unit)
output += '<item label="%s: %s" />' % (tt['humidity'], current_conditions['humidity'])
output += '<item label="%s: %s" />' % (tt['wind'], current_conditions['wind_condition'])
for forecast in forecasts:
output += '\n<separator label="%s: %s" />' % (tt['forecast'], forecast['day_of_week'])
output += '<item label="%s: %s" />' % (tt['weather'], forecast['condition'])
output += '<item label="%s: %s %s" />' % ( tt['mintemp'], forecast['low'], temp_unit )
output += '<item label="%s: %s %s" />' % ( tt['maxtemp'], forecast['high'], temp_unit )
output += '\n</openbox_pipe_menu>'
return output.encode('utf-8')
cache_file = join(os.getenv("HOME"), '.gweather.cache')
try:
f = open(cache_file,'rb')
cache = pickle.load(f)
f.close()
except IOError:
cache = None
if cache == None or (city, lang) not in cache or (
cache[(city, lang)]['date'] + timedelta(hours=CACHE_HOURS) < datetime.utcnow()):
# The cache is outdated
weather = get_weather(city, lang)
ob_pipe_menu = get_openbox_pipe_menu(lang, **weather)
print ob_pipe_menu
if cache == None:
cache = dict()
cache[(city, lang)] = {'date': datetime.utcnow(), 'ob_pipe_menu': ob_pipe_menu}
#Save the data in the cache
try:
f = open(cache_file, 'wb')
cache = pickle.dump(cache, f, -1)
f.close()
except IOError:
raise
else:
print cache[(city, lang)]['ob_pipe_menu']
Examples:
$ python .config/openbox/scripts/gweather3.py "New York" en
<openbox_pipe_menu>
<separator label="New York, NY (2009-07-17)" />
<separator label="Current conditions" /><item label="Weather: Clear" /><item label="Temperature: 79 F" /><item label="Humidity: Humidity: 66%" /><item label="Wind: Wind: N at 5 mph" />
<separator label="Forecast: Fri" /><item label="Weather: Chance of Storm" /><item label="Minimun Temperature: 70 F" /><item label="Maximun Temperature: 90 F" />
<separator label="Forecast: Sat" /><item label="Weather: Chance of Storm" /><item label="Minimun Temperature: 65 F" /><item label="Maximun Temperature: 85 F" />
<separator label="Forecast: Sun" /><item label="Weather: Mostly Sunny" /><item label="Minimun Temperature: 63 F" /><item label="Maximun Temperature: 83 F" />
<separator label="Forecast: Mon" /><item label="Weather: Chance of Showers" /><item label="Minimun Temperature: 65 F" /><item label="Maximun Temperature: 81 F" />
</openbox_pipe_menu>
$ python .config/openbox/scripts/gweather3.py "New York" es
<openbox_pipe_menu>
<separator label="New York, NY (2009-07-17)" />
<separator label="Actualmente" /><item label="Tiempo: Despejado" /><item label="Temperatura: 26 °C" /><item label="Humedad: Humedad: 66%" /><item label="Viento: Viento: N a 8 km/h" />
<separator label="Previsión: vie" /><item label="Tiempo: Posibilidad de tormenta" /><item label="Temperatura Mínima: 21 °C" /><item label="Temperatura Máxima: 32 °C" />
<separator label="Previsión: sáb" /><item label="Tiempo: Posibilidad de tormenta" /><item label="Temperatura Mínima: 18 °C" /><item label="Temperatura Máxima: 29 °C" />
<separator label="Previsión: dom" /><item label="Tiempo: Mayormente soleado" /><item label="Temperatura Mínima: 17 °C" /><item label="Temperatura Máxima: 28 °C" />
<separator label="Previsión: lun" /><item label="Tiempo: Posibilidad de chubascos" /><item label="Temperatura Mínima: 18 °C" /><item label="Temperatura Máxima: 27 °C" />
</openbox_pipe_menu>
$ python .config/openbox/scripts/gweather3.py "New York" fr
<openbox_pipe_menu>
<separator label="New York, NY (2009-07-17)" />
<separator label="Actuel" /><item label="Météo: Temps clair" /><item label="Température: 26 °C" /><item label="Humidité: Humidité : 66 %" /><item label="Vent: Vent : N à 8 km/h" />
<separator label="Prévision: ven." /><item label="Météo: Risques de tempête" /><item label="Température minimale: 21 °C" /><item label="Température maximale: 32 °C" />
<separator label="Prévision: sam." /><item label="Météo: Risques de tempête" /><item label="Température minimale: 18 °C" /><item label="Température maximale: 29 °C" />
<separator label="Prévision: dim." /><item label="Météo: Ensoleillé dans l'ensemble" /><item label="Température minimale: 17 °C" /><item label="Température maximale: 28 °C" />
<separator label="Prévision: lun." /><item label="Météo: Risques d'averses" /><item label="Température minimale: 18 °C" /><item label="Température maximale: 27 °C" />
</openbox_pipe_menu>
$ python .config/openbox/scripts/gweather3.py "New York" de
<openbox_pipe_menu>
<separator label="New York, NY (2009-07-17)" />
<separator label="Aktuell" /><item label="Wetter: Klar" /><item label="Temperatur: 26 °C" /><item label="Luftfeuchtigkeit: Feuchtigkeit: 66 %" /><item label="Wind: Wind: N mit 8 km/h" />
<separator label="Prognostizieren: Fr." /><item label="Wetter: Vereinzelt stürmisch" /><item label="Minimale Temperatur: 21 °C" /><item label="Höchste Temperatur: 32 °C" />
<separator label="Prognostizieren: Sa." /><item label="Wetter: Vereinzelt stürmisch" /><item label="Minimale Temperatur: 18 °C" /><item label="Höchste Temperatur: 29 °C" />
<separator label="Prognostizieren: So." /><item label="Wetter: Meist sonnig" /><item label="Minimale Temperatur: 17 °C" /><item label="Höchste Temperatur: 28 °C" />
<separator label="Prognostizieren: Mo." /><item label="Wetter: Vereinzelte Schauer" /><item label="Minimale Temperatur: 18 °C" /><item label="Höchste Temperatur: 27 °C" />
</openbox_pipe_menu>
$ python .config/openbox/scripts/gweather3.py "Göttingen" de
<openbox_pipe_menu>
<separator label="Göttingen, NDS (2009-07-17)" />
<separator label="Aktuell" /><item label="Wetter: Meistens bewölkt" /><item label="Temperatur: 21 °C" /><item label="Luftfeuchtigkeit: Feuchtigkeit: 49 %" /><item label="Wind: Wind: SW mit 13 km/h" />
<separator label="Prognostizieren: Fr." /><item label="Wetter: Meist sonnig" /><item label="Minimale Temperatur: 13 °C" /><item label="Höchste Temperatur: 23 °C" />
<separator label="Prognostizieren: Sa." /><item label="Wetter: Vereinzelt Regen" /><item label="Minimale Temperatur: 11 °C" /><item label="Höchste Temperatur: 16 °C" />
<separator label="Prognostizieren: So." /><item label="Wetter: Vereinzelt stürmisch" /><item label="Minimale Temperatur: 12 °C" /><item label="Höchste Temperatur: 17 °C" />
<separator label="Prognostizieren: Mo." /><item label="Wetter: Vereinzelt Regen" /><item label="Minimale Temperatur: 10 °C" /><item label="Höchste Temperatur: 20 °C" />
</openbox_pipe_menu>
Last edited by noalwin (2009-07-17 20:50:19)
Offline
If you look at humidity and wind, you will see that the text is shown twice. I fixed this, and also added Swedish translation!
#!/usr/bin/python -o
# -*- coding: utf-8 -*-
from urllib import urlopen, quote
from xml.etree.cElementTree import parse
from datetime import datetime, timedelta
import os
from os.path import join
from sys import argv
try:
import cPickle as pickle
except ImportError:
import pickle
TRANSLATED_TEXT = {
'en': {
'current': 'Current conditions',
'weather': 'Weather',
'temp': 'Temperature',
'forecast': 'Forecast',
'mintemp': 'Minimun Temperature',
'maxtemp': 'Maximun Temperature'
},
'sv': {
'current': u'Aktuell prognos',
'weather': u'Väder',
'temp': u'Temperatur',
'forecast': u'Prognos',
'mintemp': u'Lägsta temperatur',
'maxtemp': u'Högsta temperatur'
},
'es': {
'current': u'Actualmente',
'weather': u'Tiempo',
'temp': u'Temperatura',
'forecast': u'Previsión',
'mintemp': u'Temperatura Mínima',
'maxtemp': u'Temperatura Máxima'
},
'fr': {
'current': u'Actuel',
'weather': u'Météo',
'temp': u'Température',
'forecast': u'Prévision',
'mintemp': u'Température minimale',
'maxtemp': u'Température maximale'
},
'de': {
'current': u'Aktuell',
'weather': u'Wetter',
'temp': u'Temperatur',
'forecast': u'Prognostizieren',
'mintemp': u'Minimale Temperatur',
'maxtemp': u'Höchste Temperatur'
}
}
if len(argv) != 3:
raise Exception('Usage: gweather.py city language.')
else:
city = argv[1]
lang = argv[2]
CACHE_HOURS = 1
WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s&oe=UTF-8'
def get_weather(city, lang):
url = WEATHER_URL % (quote(city), quote(lang))
data = parse(urlopen(url))
forecasts = []
for forecast in data.findall('weather/forecast_conditions'):
forecasts.append(
dict([(element.tag, element.get("data")) for element in forecast.getchildren()]))
return {
'forecast_information': dict([(element.tag, element.get("data")) for element in data.find('weather/forecast_information').getchildren()]),
'current_conditions': dict([(element.tag, element.get("data")) for element in data.find('weather/current_conditions').getchildren()]),
'forecasts': forecasts
}
def get_openbox_pipe_menu(lang, forecast_information, current_conditions, forecasts):
if lang == 'en-US':
lang = 'en'
tt = TRANSLATED_TEXT[lang]
temp_var, temp_unit = ("temp_c", u"\u00b0C") if forecast_information['unit_system'] == "SI" else ("temp_f", "F")
output = '<openbox_pipe_menu>'
output += '\n<separator label="%s (%s)" />' % (weather['forecast_information']['city'],forecast_information['forecast_date'])
output += '\n<separator label="%s" />' % tt['current']
output += '<item label="%s: %s" />' % (tt['weather'], current_conditions['condition'])
output += '<item label="%s: %s %s" />' % (tt['temp'], current_conditions[temp_var], temp_unit)
output += '<item label="%s" />' % (current_conditions['humidity'])
output += '<item label="%s" />' % (current_conditions['wind_condition'])
for forecast in forecasts:
output += '\n<separator label="%s: %s" />' % (tt['forecast'], forecast['day_of_week'])
output += '<item label="%s: %s" />' % (tt['weather'], forecast['condition'])
output += '<item label="%s: %s %s" />' % ( tt['mintemp'], forecast['low'], temp_unit )
output += '<item label="%s: %s %s" />' % ( tt['maxtemp'], forecast['high'], temp_unit )
output += '\n</openbox_pipe_menu>'
return output.encode('utf-8')
cache_file = join(os.getenv("HOME"), '.gweather.cache')
try:
f = open(cache_file,'rb')
cache = pickle.load(f)
f.close()
except IOError:
cache = None
if cache == None or (city, lang) not in cache or (
cache[(city, lang)]['date'] + timedelta(hours=CACHE_HOURS) < datetime.utcnow()):
# The cache is outdated
weather = get_weather(city, lang)
ob_pipe_menu = get_openbox_pipe_menu(lang, **weather)
print ob_pipe_menu
if cache == None:
cache = dict()
cache[(city, lang)] = {'date': datetime.utcnow(), 'ob_pipe_menu': ob_pipe_menu}
#Save the data in the cache
try:
f = open(cache_file, 'wb')
cache = pickle.dump(cache, f, -1)
f.close()
except IOError:
raise
else:
print cache[(city, lang)]['ob_pipe_menu']
Another thing I notised was that you used quotes "" around the city, if you do that in the menu, it wont work. Just thought I'd help someone out a bit!
Also, I did a script to run the commands, and put it in /etc/cron.hourly/ to avoid the menu geting stuck every hour!
Thanks for this awsome script!
Last edited by LAltinell (2009-07-24 23:16:39)
Offline
Another thing I notised was that you used quotes "" around the city, if you do that in the menu, it wont work. Just thought I'd help someone out a bit!
Also, I did a script to run the commands, and put it in /etc/cron.hourly/ to avoid the menu geting stuck every hour!Thanks for this awsome script!
Could you explain better the problem with the quotes ""?
They shouldn't be problematic, unless the city name also had quotes on it.
Offline
Yes you might or you should rewrite the script in a more elegant way to make it better..
__________________
Crawl space dehumidifier
Offline
How do you make output separated? I want to separate current from forecast.
Like it is on your screenshots.
Offline
Do you need a extra "Forecast" separator like in the original screenshot?
Add
output += '\n<separator label="Forecast" />'
before the
for forecast in forecasts:
I think that it will do what you need
Last edited by noalwin (2010-03-08 21:04:35)
Offline
I am not an openbox user but I thought I should post as I think you have another option to create weather output like this....I think, I hope I am not stepping on any toes.
You may be able to create a menu from my conkyForecast python script and a suitable template file (packaged as conkyforecast-bzr in AUR, weather data sourced from weather.com). The template would contain the menu text with place holders for the data, that's assuming printed output with the right structure is all you need for pipe menus? The original ubuntu thread on the script is here: http://ubuntuforums.org/showthread.php?t=869328
Offline
Do you need a extra "Forecast" separator like in the original screenshot?
Add
output += '\n<separator label="Forecast" />'
before the
for forecast in forecasts:
I think that it will do what you need
Yes, thats it. Ty
Offline
Use en-GB as the language option to get SI units in forecasts from iGoogle.
This altered code will make it work.
For fun, I also changed date to date plus UTC using 'current_date_time' instead of 'forecast_date':
#!/usr/bin/python -o
# -*- coding: utf-8 -*-
from urllib import urlopen, quote
from xml.etree.cElementTree import parse
from datetime import datetime, timedelta
import os
from os.path import join
from sys import argv
try:
import cPickle as pickle
except ImportError:
import pickle
TRANSLATED_TEXT = {
'en': {
'current': 'Current conditions',
'weather': 'Weather',
'temp': 'Temperature',
'humidity': 'Humidity',
'wind': 'Wind',
'forecast': 'Forecast',
'mintemp': 'Minimum Temperature',
'maxtemp': 'Maximum Temperature'
},
'sv': {
'current': u'Aktuell prognos',
'weather': u'Väder',
'temp': u'Temperatur',
'forecast': u'Prognos',
'mintemp': u'Lägsta temperatur',
'maxtemp': u'Högsta temperatur'
},
'es': {
'current': u'Actualmente',
'weather': u'Tiempo',
'temp': u'Temperatura',
'humidity': u'Humedad',
'wind': u'Viento',
'forecast': u'Previsión',
'mintemp': u'Temperatura Mínima',
'maxtemp': u'Temperatura Máxima'
},
'fr': {
'current': u'Actuel',
'weather': u'Météo',
'temp': u'Température',
'humidity': u'Humidité',
'wind': u'Vent',
'forecast': u'Prévision',
'mintemp': u'Température minimale',
'maxtemp': u'Température maximale'
},
'de': {
'current': u'Aktuell',
'weather': u'Wetter',
'temp': u'Temperatur',
'humidity': u'Luftfeuchtigkeit',
'wind': u'Wind',
'forecast': u'Prognostizieren',
'mintemp': u'Minimale Temperatur',
'maxtemp': u'Höchste Temperatur'
}
}
if len(argv) != 3:
raise Exception('Usage: gweather2.py city language.')
else:
city = argv[1]
lang = argv[2]
CACHE_HOURS = 1
WEATHER_URL = 'http://www.google.com.au/ig/api?weather=%s&hl=%s&oe=UTF-8'
def get_weather(city, lang):
url = WEATHER_URL % (quote(city), quote(lang))
data = parse(urlopen(url))
forecasts = []
for forecast in data.findall('weather/forecast_conditions'):
forecasts.append(
dict([(element.tag, element.get("data")) for element in forecast.getchildren()]))
return {
'forecast_information': dict([(element.tag, element.get("data")) for element in data.find('weather/forecast_information').getchildren()]),
'current_conditions': dict([(element.tag, element.get("data")) for element in data.find('weather/current_conditions').getchildren()]),
'forecasts': forecasts
}
def get_openbox_pipe_menu(lang, forecast_information, current_conditions, forecasts):
if lang == 'en-US':
lang = 'en'
#this solves the English language SI units problem
if lang == 'en-GB':
lang = 'en'
tt = TRANSLATED_TEXT[lang]
temp_var, temp_unit = ("temp_c", u"\u00b0C") if forecast_information['unit_system'] == "SI" else ("temp_f", "F")
output = '<openbox_pipe_menu>'
output += '\n<separator label="%s (%s)" />' % (weather['forecast_information']['city'],forecast_information['current_date_time'])
output += '\n<separator label="%s" />' % tt['current']
output += '<item label="%s: %s" />' % (tt['weather'], current_conditions['condition'])
output += '<item label="%s: %s %s" />' % (tt['temp'], current_conditions[temp_var], temp_unit)
output += '<item label="%s" />' % (current_conditions['humidity'])
output += '<item label="%s" />' % (current_conditions['wind_condition'])
for forecast in forecasts:
output += '\n<separator label="%s: %s" />' % (tt['forecast'], forecast['day_of_week'])
output += '<item label="%s: %s" />' % (tt['weather'], forecast['condition'])
output += '<item label="%s: %s %s" />' % ( tt['mintemp'], forecast['low'], temp_unit )
output += '<item label="%s: %s %s" />' % ( tt['maxtemp'], forecast['high'], temp_unit )
output += '\n</openbox_pipe_menu>'
return output.encode('utf-8')
cache_file = join(os.getenv("HOME"), '.gweather.cache')
try:
f = open(cache_file,'rb')
cache = pickle.load(f)
f.close()
except IOError:
cache = None
if cache == None or (city, lang) not in cache or (
cache[(city, lang)]['date'] + timedelta(hours=CACHE_HOURS) < datetime.utcnow()):
# The cache is outdated
weather = get_weather(city, lang)
ob_pipe_menu = get_openbox_pipe_menu(lang, **weather)
print ob_pipe_menu
if cache == None:
cache = dict()
cache[(city, lang)] = {'date': datetime.utcnow(), 'ob_pipe_menu': ob_pipe_menu}
#Save the data in the cache
try:
f = open(cache_file, 'wb')
cache = pickle.dump(cache, f, -1)
f.close()
except IOError:
raise
else:
print cache[(city, lang)]['ob_pipe_menu']
Last edited by bcebul (2010-06-06 06:04:21)
Offline
Yes you might or you should rewrite the script in a more elegant way to make it better..
__________________
Crawl space dehumidifier
Or you can learn what the hell escape codes are, kiddo.
Last edited by kevr (2010-09-18 02:16:20)
Kevin Morris <kevr@0cost.org>
Hangs out in #archlinux-aurweb. Loves the AUR.
Offline
Hello,
I'm trying to get the version of the pipe menu based on Yahoo weather working. Here's the script again.
#!/usr/bin/python
import urllib
from xml.etree.cElementTree import parse
from datetime import datetime, timedelta
import os
from os.path import join
from sys import argv
try:
import cPickle as pickle
except ImportError:
import pickle
#Usage: yweather.py AYXX0001 Celsius
if len(argv) != 3:
raise Exception('Usage: yweather.py zip_code units. zip_code is your city code in Yahoo Weather, units can be Celsius or Fahrenheit.')
else:
zip_code = argv[1]
if argv[2] == 'Fahrenheit' or argv[2] == 'fahrenheit':
units = 'f'
else:
units = 'c'
CACHE_HOURS = 6
#http://weather.yahooapis.com/forecastrss
WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s&u=%s'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
def weather_for_zip(zip_code, units):
url = WEATHER_URL % (zip_code, units)
rss = parse(urllib.urlopen(url)).getroot()
forecasts = []
for element in rss.findall('channel/item/{%s}forecast' % WEATHER_NS):
forecasts.append(dict(element.items()))
ycondition = rss.find('channel/item/{%s}condition' % WEATHER_NS)
return {
'current_condition': dict(ycondition.items()),
'forecasts': forecasts,
'title': rss.findtext('channel/title'),
'pubDate': rss.findtext('channel/item/pubDate'), #rss.findtext('channel/lastBuildDate'),
'location': dict(rss.find('channel/{%s}location' % WEATHER_NS).items()),
'wind': dict(rss.find('channel/{%s}wind' % WEATHER_NS).items()),
'atmosphere': dict(rss.find('channel/{%s}atmosphere' % WEATHER_NS).items()),
'astronomy': dict(rss.find('channel/{%s}astronomy' % WEATHER_NS).items()),
'units': dict(rss.find('channel/{%s}units' % WEATHER_NS).items())
}
def print_openbox_pipe_menu(weather):
print '<openbox_pipe_menu>'
print '<separator label="%s %s" />' % (weather['location']['city'],weather['pubDate'])
print '<separator label="Current conditions" />'
print '<item label="Weather: %s" />' % weather['current_condition']['text']
print '<item label="Temperature: %s %s" />' % ( weather['current_condition']['temp'],
weather['units']['temperature'] )
print '<item label="Humidity: %s%%" />' % weather['atmosphere']['humidity']
print '<item label="Visibility: %s %s" />' % ( weather['atmosphere']['visibility'],
weather['units']['distance'] )
#pressure: steady (0), rising (1), or falling (2)
if weather['atmosphere']['rising'] == 0:
pressure_state = 'steady'
elif weather['atmosphere']['rising'] == 1:
pressure_state = 'rising'
else:
pressure_state = 'falling'
print '<item label="Pressure: %s %s (%s)" />' % ( weather['atmosphere']['pressure'],
weather['units']['pressure'], pressure_state )
print '<item label="Wind chill: %s %s" />' % ( weather['wind']['chill'],
weather['units']['temperature'] )
print '<item label="Wind direction: %s degrees" />' % weather['wind']['direction']
print '<item label="Wind speed: %s %s" />' % ( weather['wind']['speed'],
weather['units']['speed'] )
print '<item label="Sunrise: %s" />' % weather['astronomy']['sunrise']
print '<item label="Sunset: %s" />' % weather['astronomy']['sunset']
for forecast in weather['forecasts']:
print '<separator label="Forecast: %s" />' % forecast['day']
print '<item label="Weather: %s" />' % forecast['text']
print '<item label="Min temperature: %s %s" />' % ( forecast['low'],
weather['units']['temperature'] )
print '<item label="Max temperature: %s %s" />' % ( forecast['high'],
weather['units']['temperature'] )
print '</openbox_pipe_menu>'
cache_file = join(os.getenv("HOME"), '.yweather.cache')
try:
f = open(cache_file,'rb')
cache = pickle.load(f)
f.close()
except IOError:
cache = None
if cache == None or (zip_code, units) not in cache or (
cache[(zip_code, units)]['date'] + timedelta(hours=CACHE_HOURS) < datetime.utcnow()):
# The cache is outdated
weather = weather_for_zip(zip_code, units)
if cache == None:
cache = dict()
cache[(zip_code, units)] = {'date': datetime.utcnow(), 'weather': weather}
#Save the data in the cache
try:
f = open(cache_file, 'wb')
cache = pickle.dump(cache, f, -1)
f.close()
except IOError:
raise
else:
weather = cache[(zip_code, units)]['weather']
print_openbox_pipe_menu(weather)
I have a problem which seems to be about confusion between locations:
The pipe menu works, i.e. shows in my obmenu, when I use my own zip code, 00840 in Helsinki, Finland. However, whilst Yahoo Weather's online search brings up my city as the first alternative, due to my IP addy I'm sure, the python script brings up the information for Frederiksted, Virgin Islands, U.S. on the same zip code.
Running the script with any other zip codes of my city (all of which the Yahoo weather search finds but most of which are in use in some other part of the world as well) produces the following:
$ python ~/.config/openbox/scripts/yweather.py 00530 Celsius
Traceback (most recent call last):
File "/home/maria/.config/openbox/scripts/yweather.py", line 100, in <module> weather =
weather_for_zip(zip_code, units)
File "/home/maria/.config/openbox/scripts/yweather.py", line 41, in weather_for_zip
'current_condition': dict(ycondition.items()),
AttributeError: 'NoneType' object has no attribute 'items'
So, my question is: how should I modify the script so that it either can select the correct one from the various locations for the zip code (based on ip address?) or searches for city rather than zip code?
Offline
Offline
Actually, sorry, only understood that I need to dig up the Yahoo weather code for Helsinki, Finland.
Offline
This script/pipe menu still works and might come in even handier since weather.com changed their api taking away the free accounts.
But, some changes in python needs to be corrected for; to run the script do;
python2 gweather.py city langauge
and if copying the whole script from this thread look out for unwanted linebreaks!
Offline
I've run into an issue with the initial script (still works fine for almost every location used): when the name of the city has an apostrophe (') inside, such as the capital of Chad (N'Djamena), the script fails to be parsed properly in the menu and therefore Openbox returns an error. Does anyone with Python knowledge see where in the script things are going wrong?
I'd really like to have the weather readout for that city if possible. Thanks for your assistance.
Note: Even though I can reference the city N'Djamena properly by not including the apostrophe when running the command via terminal
$ python2 ~/.scripts/weatherpipe.py Ndjamena
the problem is related to how Google's API returns the following output (italicized part):
<openbox_pipe_menu>
<separator label='N'Djamena, N'Djamena' />
<separator label='Current condidtions' />
<item label='Weather: Clear' />
<item label='Temperature 66 F' />
<item label='Humidity: 37%' />
<item label='Wind: NE at 9 mph' />
<separator label='Forecast' />
<separator label='Thursday' />
.
.
.
EDIT: Okay, should have googled better first... the solution is to change the script as noted here:
http://crunchbanglinux.org/forums/post/20484/#p20484
Good luck!
Last edited by bkadoctaj (2012-01-12 03:26:18)
Offline
I just wanted to follow up with a change a friend and I made to the initial Google API weather pipe menu script offered here:
#!/usr/bin/python2
import sys
import urllib2
from string import maketrans
#from xml.sax import make_parser, handler
from xml.sax import handler, parseString
class ElementProcesser(handler.ContentHandler):
def startElement(self, name, attrs):
if name == "city":
print "<separator label=\"" + attrs["data"].encode('utf-8','replace') + "\" />"
elif name == "current_conditions":
print "<separator label='Current conditions' />"
elif name == "condition":
print "<item label='Weather: " + attrs["data"] + "' />"
elif name == "humidity":
print "<item label='" + attrs["data"] + "' />"
elif name == "wind_condition":
print "<item label='" + attrs["data"] + "' />"
elif name == "day_of_week":
print "<separator label='" + self.getDayOfWeek(attrs["data"]) + "' />"
#Celsius
#elif name == "temp_c":
#print "<item label='Temperature " + attrs["data"] + " C' />"
#elif name == "low":
#print "<item label='Minimum " + attrs["data"] + " C' />"
#elif name == "high":
#print "<item label='Maximum " + attrs["data"] + " C' />"
#Fahrenheit
elif name == "temp_f":
print "<item label='Temperature " + attrs["data"] + " F' />"
elif name == "low":
print "<item label='Minimum " + attrs["data"] + " F' />"
elif name == "high":
print "<item label='Maximum " + attrs["data"] + " F' />"
def endElement(self, name):
if name == "current_conditions":
print "<separator label='Forecast' />"
def startDocument(self):
print '<openbox_pipe_menu>'
def endDocument(self):
print '</openbox_pipe_menu>'
def getDayOfWeek(self,day):
#English
if day == "Mon":
return "Monday"
elif day == "Tue":
return "Tuesday"
elif day == "Wed":
return "Wednesday"
elif day == "Thu":
return "Thursday"
elif day == "Fri":
return "Friday"
elif day == "Sat":
return "Saturday"
elif day == "Sun":
return "Sunday"
else:
return day
# You should use your local version of google to have the messages in your language and metric system
for arg in sys.argv: str = arg
f = urllib2.urlopen("http://www.google.com/ig/api?ie=utf8&oe=utf8&weather="+str)
xml = f.read()
f.close()
#Avoid problems with non english characters
trans=maketrans("\xe1\xe9\xed\xf3\xfa","aeiou")
xml = xml.translate(trans)
#print xml
#parser.parse("http://www.google.es/ig/api?weather="+sys.argv[1])
parseString(xml,ElementProcesser())
http://http://pastebin.com/v4trEpAJ
The main changes can be found in line 13. When calling the script, one should use the following form, where Foo Bar is the city/town.
$ python2 ~/.scripts/weatherpipe.py -c 'foo+bar'
[i.e. you must place the '+' wherever there is a ' ' (space)]
This script only functions in English as currently written.
Last edited by bkadoctaj (2012-01-13 23:31:22)
Offline
Final project complete:
World capitals all listed in a pipe menu with icons...
Offline
i know this is a little old but i need some help...i am having the same problem as zephyrus17 with the latest version of the script. i have commented out the F section and un-commented the C section but this is the output i get
~/.config/openbox/script $ python weather2.py -c "Moncton"
<openbox_pipe_menu>
<separator label="Moncton, NB" />
<separator label='Current conditions' />
<item label='Weather: Fog' />
<item label='Temperature: -4 C' />
<item label='Humidity: 100%' />
<item label='Wind: N at 7 mph' />
<separator label='Forecast' />
<separator label='Thursday' />
<item label='Minimum: 16 C' />
<item label='Maximum: 36 C' />
<item label='Weather: Fog' />
<separator label='Friday' />
<item label='Minimum: 25 C' />
<item label='Maximum: 37 C' />
<item label='Weather: Chance of Snow' />
<separator label='Saturday' />
<item label='Minimum: 18 C' />
<item label='Maximum: 36 C' />
<item label='Weather: Mostly Sunny' />
<separator label='Sunday' />
<item label='Minimum: 5 C' />
<item label='Maximum: 32 C' />
<item label='Weather: Fog' />
</openbox_pipe_menu>
what else must i change? thanx for this script i love it.
Offline
@grondinm
I am using the version posted by bcebul above.
This is my openbox menu entry;
<menu execute="python2 ~/scripts/weatherpipe.py Gralingen,Luxembourg en-GB" id="pipe-weather" label="Weather"/>
I had a problem with using 'current_date_time';
<separator label="Gralingen, Diekirch (1970-01-01 00:00:00 +0000)" />
So I reverted to 'forecast_date' as per original script.
This screengrab shows the problem with 'current_date_time';
Also, the script appears to add another symbol before the Celcius symbol so there is a space I would like to get rid of...;
4 °C
Offline
thanx that worked great.
Offline
I can not get this to work on my arch. Every step I have follow, but when I hover over menu it gives my error. I have just tried both setups. The y and g version. Still no action. There has to be something I'm missing.
Last edited by jedijimi (2014-01-06 20:00:21)
Crude matter we are not, Luminous beings we are
Offline