Ver clima de nuestra ciudad II: usando conky
En la anterior entrada, vimos como añadir el tiempo de nuestra ciudad, al menú de openbox: http://behindopendoors.netne.net/blog/linux/ver-el-clima-de-nuestra-ciudad-en-openbox.
Ahora, vamos a visualizarlo, usando el mismo script pero mediante conky, por lo que lo podremos usar en cualquier distro y entorno de escritorio, solo tendremos que instalar previamente conky (lo encontraréis en repositorios).
Lo primero, tendremos que usar, el script escrito en python, que modificado un poco (copiad el texto, y pegarlo en un archivo). Yo lo guardo en la ruta ~/.config/openbox/scripts/gweather-conky2.py, pero podéis ponerlo donde queráis.
#!/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 += '%s\n' % (current_conditions['condition'])
output += '%s: %s %s\n' % (tt['temp'], current_conditions[temp_var], temp_unit)
output += '%s\n' % (current_conditions['humidity'])
output += '%s' % (current_conditions['wind_condition'])return output.encode('utf-8')
cache_file = join(os.getenv("HOME"), '.gweather-conky2.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']
Bien, ahora tenemos que crear el archivo de configuración de conky:
# set to yes if you want Conky to be forked in the background
background yes
# Use Xft?
use_xft yes
xftfont Dejavu Sans:pixelsize=11
# Update interval in seconds
update_interval 1
# This is the number of times Conky will update before quitting.
# Set to zero to run forever.
total_run_times 0
# Create own window instead of using desktop (required in nautilus)
own_window yes
own_window_transparent yes
own_window_type normal
own_window_hints undecorate,below,sticky,skip_taskbar,skip_pager
# Use double buffering (reduces flicker, may not work for everyone)
double_buffer yes
# Minimum size of text area
minimum_size 160
maximum_width 200
# Draw shades?
draw_shades no
# Draw outlines?
draw_outline no
# Draw borders around text
draw_borders yes
# Stippled borders?
stippled_borders 0
# border margins
border_margin 3
# border width
border_width 0
# Default colors and also border colors
default_color 404040
#default_shade_color white
#default_outline_color black
own_window_colour 3c3c3c
# Text alignment, other possible values are commented
#alignment top_left
alignment top_right
#alignment bottom_left
#alignment bottom_right
# Gap between borders of screen and text
# same thing as passing -x at command line
gap_x 15
gap_y 70
# Subtract file system buffers from used memory?
no_buffers yes
# set to yes if you want all text to be in uppercase
uppercase yes
# number of cpu samples to average
# set to 1 to disable averaging
cpu_avg_samples 2
# number of net samples to average
# set to 1 to disable averaging
net_avg_samples 2
# Force UTF8? note that UTF8 support required XFT
override_utf8_locale yes
# Add spaces to keep things from moving about? This only affects certain objects.
use_spacer right
TEXT
${color #000000}${execi 12 python ~/.config/openbox/scripts/gweather-conky2.py bilbao es;}
Este archivo, lo guardais con el nombre de .conkyrc, y lo ponéis en vuestra home. Si queréis, podéis usar más de un conky al mismo tiempo (este solo os dará el tiempo, a no ser que le añadáis código).
Tenéis que prestar especial atención a la última linea del conky: ${color #000000}${execi 12 python ~/.config/openbox/scripts/gweather-conky2.py bilbao es;} . Podéis cambiar el color, variando los números, la frecuencia con la que se ejecuta el script (12 segundos por defecto, aunque el script de python no se refresca con tanta frecuencia), la ruta donde dejasteis el script (editarla correctamente) y por último, el nombre de vuestra ciudad (si tiene espacios, poner un guión, por ejemplo: buenos-aires), y por el último, poned es, que es el idioma, no el país de vuestra ciudad.
Si todo ha ido bien, lograréis el siguiente efecto:
Se puede modificar el script de python, para que nos muestre otros datos, o los ordene de otra manera, si sabéis un poco de programación básica, no os será difícil. También podéis añadir datos de temperatura, voltaje y velocidad de los ventiladores: http://behindopendoors.netne.net/blog/linux/lm-sensors-monitoriza-la-temperatura-velocidad-de-los-ventiladores-y-sus-voltajes










Últimos comentarios