Ver el clima de nuestra ciudad I: Menú de Openbox
Puede que algo tan sencillo como ver el clima de nuestra ciudad, en nuestro entorno de escritorio, se complique. Seguramente habrá un montón de opciones, yo os voy a ofrecer una liviana, fácil de configurar, y que a mí me parece elegante. Una imagen vale más que mil palabras, así que…
Para incluir el clima en el menú de openbox, usé un script escrito en python, que posteó un usuario en el foro de Arch: http://bbs.archlinux.org/viewtopic.php?id=43432.
El script:
#!/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 = ''
output += '\n' % (weather['forecast_information']['city'],forecast_information['forecast_date'])
output += '\n' % tt['current']
output += '' % (tt['weather'], current_conditions['condition'])
output += '' % (tt['temp'], current_conditions[temp_var], temp_unit)
output += '' % (tt['humidity'], current_conditions['humidity'])
output += '' % (tt['wind'], current_conditions['wind_condition'])
for forecast in forecasts:
output += '\n' % (tt['forecast'], forecast['day_of_week'])
output += '' % (tt['weather'], forecast['condition'])
output += '' % ( tt['mintemp'], forecast['low'], temp_unit )
output += '' % ( tt['maxtemp'], forecast['high'], temp_unit )
output += '\n'
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']
Lo guardamos en el directorio que queramos, yo lo dejé en ~/.config/openbox/scripts/gweather.py, pero da lo mismo. Para ejecutarlo:
python ~/.config/openbox/scripts/gweather.py YOURCITY IDIOMA
El idioma, podemos escoger entre es, de, fr, o de. Y el nombre de nuestra ciudad en minúsculas, si tiene espacios lo pondremos con un guión de la siguiente forma: buenos-aires.
Ahora vamos a insertar el script en el menú de openbox, de la siguiente manera, editando el archivo ~/.config/openbox/menu.xml:
añadimos la siguiente linea, donde queramos que aparezca en el menú (a nuestro gusto).
<menu id="pipe-weather" label="Weather" execute="python ~/.config/openbox/scripts/gweather.py bilbao es" />
Y ya está todo listo. Este script lo podemos usar con otras aplicaciones, modificando el output editando el codigo python, o con pipes, el único limite es nuestra imaginación (y los conocimientos de programación). En el proximo artículo, explicaré como usarlo conjuntamente con el monitor del sistema conky.
P.D: Agradecer al autor, o autores que se han currado el script, y espero que funcione por mucho tiempo y no cambien la web
.






Últimos comentarios