LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: Kevin_Chou

show下桌面

[复制链接]
发表于 2009-5-6 13:12:41 | 显示全部楼层
Post by hhf3498;1984049
有在笔记本上用conky来显示电池使用状况的么?


可以,试试这句
${font}${color slate grey}电池电量alignr${color}${battery_percent BAT1}%
回复 支持 反对

使用道具 举报

发表于 2009-5-6 13:20:30 | 显示全部楼层
好花的桌面呀
现在习惯了awesome,根本都不用看界面了
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-5-6 14:21:40 | 显示全部楼层
再来两张关了COMPIZ的,换了张壁纸,没那么花了。
用了一会,感觉壁纸太亮了,有点刺眼,等把对比度调整一下。
awesome和gnome都装了,awesome简约点,gnome就华丽点吧。





回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-5-6 14:28:10 | 显示全部楼层
conky配置文件

  1. background yes
  2. use_xft yes
  3. xftfont Radio Space:style=Bold:size=8
  4. xftalpha 0.8
  5. mail_spool $MAIL
  6. update_interval 1.0
  7. total_run_times 0
  8. own_window yes
  9. own_window_type override
  10. own_window_transparent yes
  11. own_window_colour black
  12. #own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager
  13. double_buffer yes
  14. minimum_size 280 5
  15. maximum_width 300
  16. draw_shades yes
  17. draw_outline no
  18. draw_borders no
  19. draw_graph_borders no
  20. stippled_borders 8
  21. border_margin 4
  22. border_width 1
  23. default_color white
  24. default_shade_color black
  25. default_outline_color black
  26. #alignment top_left
  27. #alignment top_right
  28. #alignment middle_left
  29. #alignment middle_right
  30. alignment bottom_left
  31. #alignment bottom_right
  32. #alignment none
  33. gap_x 12
  34. gap_y -180
  35. no_buffers yes
  36. uppercase no
  37. cpu_avg_samples 2
  38. net_avg_samples 2
  39. override_utf8_locale yes
  40. use_spacer none

  41. # ${font Martin Vogel's Symbols:size=24}${color #16A90E}j$color${voffset -4}${font Xirod:size=6}${exec whoami} at $nodename on $machine
  42. # ${font Verdana:style=Bold:size=9}CPU ${font Verdana:size=8}${freq} MHZ

  43. TEXT
  44. ${font Xirod:style=Bold:size=6}${exec whoami} at $nodename on $machine
  45. $hr
  46. ${font Radio Space:style=Bold:size=14}${color1}${time %Y-%m-%d}${voffset -2}${font Verana:size=10} ${time %A}
  47. ${font Xirod:size=20}${time %H:%M}${font Xirod:size=10}${time :%S}
  48. ${voffset -60}${offset 200}${font Martin Vogel's Symbols:size=40}${color white}U$color
  49. ${voffset -60}$stippled_hr
  50. ${voffset -75}${font Verdana:style=Bold:size=9}KERNEL: $font$kernel
  51. ${font Verdana:style=Bold:size=9}${color white}CPU:
  52. ${font Verdana:size=8}${color white}${execi 3600 cat /proc/cpuinfo | grep "model name" -m1 | cut -d":" -f2 | cut -d" " -f2- | sed 's#Processor ##'}
  53. ${font Verdana:style=Bold:size=9}CPU Temperature: ${font Verdana:size=8}${color green}${acpitemp}°C
  54. $alignr${cpugraph cpu1 14,190 16A90E FFFFFF}
  55. ${voffset -9}${font Verdana:style=Bold:size=9}${color #16A90E}Core 1:$color ${font Verdana:size=8}${cpu cpu1}%
  56. $alignr${cpugraph cpu2 14,190 ddaa00 E32CE1}
  57. ${voffset -9}${font Verdana:style=Bold:size=9}${color #E32CE1}Core 2:$color ${font Verdana:size=8}${cpu cpu2}%

  58. ${font Verdana:style=Bold:size=9}RAM Usage:${font Verdana:size=8}$color $mem/$memmax - $memperc% ${membar}
  59. $stippled_hr
  60. ${font Verdana:style=Bold:size=9}${color white}CPU usage$alignr PID CPU% MEM
  61. ${font Verdana:size=9}${color #ddaa00} ${top name 1}$alignr$font ${top pid 1} ${top cpu 1} ${top mem 1}
  62. ${font Verdana:size=9}${color lightgrey} ${top name 2}$alignr$font ${top pid 2} ${top cpu 2} ${top mem 2}
  63. ${font Verdana:size=9}${color lightgrey} ${top name 3}$alignr$font ${top pid 3} ${top cpu 3} ${top mem 3}

  64. ${font Verdana:style=Bold:size=9}${color white}Mem usage
  65. ${font Verdana:size=9}${color #ddaa00} ${top_mem name 1}$alignr$font ${top_mem pid 1} ${top_mem cpu 1} ${top_mem mem 1}
  66. ${font Verdana:size=9}${color lightgrey} ${top_mem name 2}$alignr$font ${top_mem pid 2} ${top_mem cpu 2} ${top_mem mem 2}
  67. ${font Verdana:size=9}${color lightgrey} ${top_mem name 3}$alignr$font ${top_mem pid 3} ${top_mem cpu 3} ${top_mem mem 3}
  68. $stippled_hr
  69. ${font Verdana:style=Bold:size=9}${color white}File system
  70. ${font Verdana:size=9}${color white}Root:${font Verdana:size=8}$color ${fs_free /} / ${fs_size /} - ${fs_free_perc /}% ${fs_bar}
  71. ${font Verdana:size=9}${color white}Home:${font Verdana:size=8}$color ${fs_free /home} / ${fs_size /home} - ${fs_free_perc /home}% ${fs_bar}

  72. ${font Verdana:style=Bold:size=9}${color white}Network
  73. ${font Verdana:size=9}${color white}IP Address: ${font DejaVu Sans Mono:size=8}$color ${addr wlan0}
  74. ${font Verdana:size=9}${color white}Total Download: ${font DejaVu Sans Mono:size=8}$color ${totaldown wlan0}
  75. ${font Verdana:size=9${color white}}Total Upload: ${font DejaVu Sans Mono:size=8}$color ${totalup wlan0}
  76. ${voffset -34}${offset 200}${font Martin Vogel's Symbols:size=36}${color #16A90E}m$color
  77. ${voffset -76}${font Verdana:size=9}${color white}Up Speed: ${font DejaVu Sans Mono:size=8}$color ${upspeed wlan0}/s
  78. ${font Verdana:size=9}${color white}Down Speed: ${font DejaVu Sans Mono:size=8}$color ${downspeed wlan0}/s
  79. $stippled_hr
  80. ${font Verdana:style=Bold:size=9}${color white}Weather
  81. ${font Verdana:size=9}${color #ddaa00}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=CN}
  82. ${font Weather:size=44}${color gold}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=WF}${font}${color}${voffset -20}${offset 18}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=CC}${offset 10}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=HT}${offset 10}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=WS} ${font Arrows:size=10}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=BF}$font
  83. ${offset 60}Sol: ${color}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=SR}-${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=SS}
  84. ${font Weather:size=26}${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=WF --startday=1 --endday=4 --spaces=1}${font}
  85. ${execi 3600 python ~/.conky/forecast.py --location=CHXX0008 --datatype=HT --startday=1 --endday=4 --spaces=11}
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-5-6 14:33:55 | 显示全部楼层
天气预报用到的python脚本forecast.py,放到~/.conky/目录下


  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ###############################################################################
  4. # forecast.py is a (not so) simple (anymore) python script to gather
  5. # details of the current weather for use in conky.
  6. #
  7. #  Author: Kaivalagi
  8. # Created: 13/04/2008
  9. # Modifications:
  10. #        14/04/2008        Allow day ranges for forecast data
  11. #        14/04/2008        Check for connectivity to xoap service
  12. #        18/04/2008        Allow the setting of spaces for ranged output
  13. #        18/04/2008        Allow Night and Day forecast output
  14. #        18/04/2008        Support locale for condition code text "CC" option, awaiting spanish language translation
  15. #        18/04/2008        Use pickling for class data rather than opening xml, this bypasses the need to interrogate cached data
  16. #        19/04/2008        Added spanish condition text - Thanks Bruce M
  17. #        19/04/2008        Added isnumeric check on all numeric output with units suffix
  18. #        19/04/2008        Altered pickle file naming to include location code
  19. #        19/04/2008        Added spanish week days conversion via locale
  20. #        20/04/2008        Added decent command argument parser
  21. #        20/04/2008        Added --shortweekday option, if given the day of week data type is shortened to 3 characters
  22. #        21/04/2008        Fixed locale options for forecast output
  23. #        21/04/2008        Added --template option to allow custom output using a single exec call :)
  24. #        21/04/2008        Added --hideunits option to remove, for example, mph and C from output
  25. #        23/04/2008        Removed --imperial option from template, this MUST be set as a standard option on the script call and not used in the template file.
  26. #        23/04/2008        Readded --imperial option to template, enabling metric or imperial values per datatype. Note when using templates command line option will not work.
  27. #        23/04/2008        Added output notifying user if the location given is bad
  28. #        24/04/2008        Added handling for no connectivity, will revert to cached data now (erroring if no cache exists). Tests by trying to open xoap.weather.com
  29. #        24/04/2008        Fixed Celsius to fahrenheit conversion
  30. #        06/05/2008        Updated url used after webservice was updated
  31. #        09/05/2008        Consolidated current condition and forecast data fetch into one call
  32. #        09/05/2008        Added Sunrise and sunset to datatypes, these are specific to both current conditions and forecast data
  33. #        09/05/2008        Added moon phase, barometer reading and barometer description to datatypes, these are only specific to current conditions and so are N/A in forecasted output
  34. #        09/05/2008        Added unit conversions for barometer from mb to inches (imperial)
  35. #   09/05/2008  Updated spanish condition text - Thanks Bruce M
  36. #   10/05/2008  Added french locale data - Thanks benpaka
  37. #   12/05/2008  Added new BF (bearing font) datatype to provide an arrow character (use with Arrow.ttf font) instead of NSEW output from WD (wind direction)
  38. #   12/05/2008  Updated WD output to be locale specific, currently supports default english and spanish - Thanks Bruce M
  39. #        18/05/2008        Added new MF (moon font) datatype to provide a moon font character (characters incorrect and no dedicated font yet).
  40. #
  41. # TODO:
  42. # Consolidate pkl files into one file/class
  43. # Add a weather font based moon phase output based on moon icon data
  44. # ??? Any more requirements out there?

  45. import sys, os, socket, urllib2, datetime, time
  46. from xml.dom import minidom
  47. from stat import *
  48. from optparse import OptionParser
  49. import locale
  50. import gettext
  51. import pickle
  52. from math import *

  53. APP="forecast.py"
  54. DIR=os.path.dirname (__file__) + '/locale'
  55. gettext.bindtextdomain(APP, DIR)
  56. gettext.textdomain(APP)
  57. _ = gettext.gettext

  58. class CommandLineParser:

  59.         parser = None

  60.         def __init__(self):

  61.                 self.parser = OptionParser()
  62.                 self.parser.add_option("-l","--location", dest="location", default="UKXX0103", type="string", metavar="CODE", help=u"location code for weather data [default: %default],Use the following url to determine your location code by city name: http://xoap.weather.com/search/search?where=Norwich")
  63.                 self.parser.add_option("-d","--datatype",dest="datatype", default="HT", type="string", metavar="DATATYPE", help=u"[default: %default] The data type options are: DW (Day Of Week), WF (Weather Font Output), LT (Low Temp), HT (High Temp), CC (Current Conditions), CT (Conditions Text), PC (Precipitation Chance), HM (Humidity), WD (Wind Direction), WS (Wind Speed), WG (Wind Gusts), CN (City Name), SR (sunrise), SS (sunset), MP (moon phase), MF (moon font), BR (barometer reading), BD (barometer description). Not applicable at command line when using templates.")
  64.                 self.parser.add_option("-s","--startday",dest="startday", type="int", metavar="NUMBER", help=u"define the starting day number, if omitted current conditions are output. Not applicable at command line when using templates.")
  65.                 self.parser.add_option("-e","--endday",dest="endday", type="int", metavar="NUMBER", help=u"define the ending day number, if omitted only starting day data is output. Not applicable at command line when using templates.")
  66.                 self.parser.add_option("-S","--spaces",dest="spaces", type="int", default=1, metavar="NUMBER", help=u"[default: %default] Define the number of spaces between ranged output. Not applicable at command line when using templates.")
  67.                 self.parser.add_option("-t","--template",dest="template", type="string", metavar="FILE", help=u"define a template file to generate output in one call. A displayable item in the file is in the form {--datatype=HT --startday=1}. The following are possible options within each item: --datatype,--startday,--endday,--night,--shortweekday,--imperial,--hideunits,--spaces . Note that the short forms of the options are not currently supported! None of these options are applicable at command line when using templates.")
  68.                 self.parser.add_option("-L","--locale",dest="locale", type="string", help=u"override the system locale for language output (en=english, es=spanish, fr=french, more to come)")
  69.                 self.parser.add_option("-i","--imperial",dest="imperial", default=False, action="store_true", help=u"request imperial units, if omitted output is in metric. Not applicable at command line when using templates.")
  70.                 self.parser.add_option("-n","--night",dest="night", default=False, action="store_true", help=u"switch output to night data, if omitted day output will be output. Not applicable at command line when using templates.")
  71.                 self.parser.add_option("-w","--shortweekday",dest="shortweekday", default=False, action="store_true", help=u"Shorten the day of week data type to 3 characters. Not applicable at command line when using templates.")
  72.                 self.parser.add_option("-u","--hideunits",dest="hideunits", default=False, action="store_true", help=u"Hide units such as mph or C, degree symbols (°) are still shown. Not applicable at command line when using templates.")
  73.                 self.parser.add_option("-v","--verbose",dest="verbose", default=False, action="store_true", help=u"request verbose output, no a good idea when running through conky!")
  74.                 self.parser.add_option("-r","--refetch",dest="refetch", default=False, action="store_true", help=u"fetch data regardless of data expiry")

  75.         def parse_args(self):
  76.                 (options, args) = self.parser.parse_args()
  77.                 return (options, args)

  78.         def print_help(self):
  79.                 return self.parser.print_help()

  80. class WeatherData:
  81.         def __init__(self, day_of_week, low, high, condition_code, condition_text, precip, humidity, wind_dir, wind_speed, wind_gusts, city, sunrise, sunset, moon_phase, moon_icon, bar_read, bar_desc):
  82.                 self.day_of_week = u""+day_of_week
  83.                 self.low = u""+low
  84.                 self.high = u""+high
  85.                 self.condition_code = u""+condition_code
  86.                 self.condition_text = u""+condition_text
  87.                 self.precip = u""+precip
  88.                 self.humidity = u""+humidity
  89.                 self.wind_dir = u""+wind_dir
  90.                 self.wind_speed = u""+wind_speed
  91.                 self.wind_gusts = u""+wind_gusts
  92.                 self.city = u""+city
  93.                 self.sunrise = u""+sunrise
  94.                 self.sunset = u""+sunset
  95.                 self.moon_phase = u""+moon_phase
  96.                 self.moon_icon = u""+moon_icon               
  97.                 self.bar_read = u""+bar_read
  98.                 self.bar_desc = u""+bar_desc


  99. class WeatherText:

  100.         conditions_text = {
  101.                 "0": _(u"Tornado"),
  102.                 "1": _(u"Tropical Storm"),
  103.                 "2": _(u"Hurricane"),
  104.                 "3": _(u"Severe Thunderstorms"),
  105.                 "4": _(u"Thunderstorms"),
  106.                 "5": _(u"Mixed Rain and Snow"),
  107.                 "6": _(u"Mixed Rain and Sleet"),
  108.                 "7": _(u"Mixed Precipitation"),
  109.                 "8": _(u"Freezing Drizzle"),
  110.                 "9": _(u"Drizzle"),
  111.                 "10": _(u"Freezing Rain"),
  112.                 "11": _(u"Showers"),
  113.                 "12": _(u"Showers"),
  114.                 "13": _(u"Snow Flurries"),
  115.                 "14": _(u"Light Snow Showers"),
  116.                 "15": _(u"Blowing Snow"),
  117.                 "16": _(u"Snow"),
  118.                 "17": _(u"Hail"),
  119.                 "18": _(u"Sleet"),
  120.                 "19": _(u"Dust"),
  121.                 "20": _(u"Fog"),
  122.                 "21": _(u"Haze"),
  123.                 "22": _(u"Smoke"),
  124.                 "23": _(u"Blustery"),
  125.                 "24": _(u"Windy"),
  126.                 "25": _(u"Cold"),
  127.                 "26": _(u"Cloudy"),
  128.                 "27": _(u"Mostly Cloudy"),
  129.                 "28": _(u"Mostly Cloudy"),
  130.                 "29": _(u"Partly Cloudy"),
  131.                 "30": _(u"Partly Cloudy"),
  132.                 "31": _(u"Clear"),
  133.                 "32": _(u"Clear"),
  134.                 "33": _(u"Fair"),
  135.                 "34": _(u"Fair"),
  136.                 "35": _(u"Mixed Rain and Hail"),
  137.                 "36": _(u"Hot"),
  138.                 "37": _(u"Isolated Thunderstorms"),
  139.                 "38": _(u"Scattered Thunderstorms"),
  140.                 "39": _(u"Scattered Thunderstorms"),
  141.                 "40": _(u"Scattered Showers"),
  142.                 "41": _(u"Heavy Snow"),
  143.                 "42": _(u"Scattered Snow Showers"),
  144.                 "43": _(u"Heavy Snow"),
  145.                 "44": _(u"Partly Cloudy"),
  146.                 "45": _(u"Thunder Showers"),
  147.                 "46": _(u"Snow Showers"),
  148.                 "47": _(u"Isolated Thunderstorms"),
  149.                 "na": _(u"N/A"),
  150.                 "-": _(u"N/A")
  151.         }

  152.         conditions_text_es = {
  153.         "0": _(u"Tornado"),
  154.         "1": _(u"Tormenta Tropical"),
  155.         "2": _(u"Huracá¡n"),
  156.         "3": _(u"Tormentas Fuertes"),
  157.         "4": _(u"Tormentas"),
  158.         "5": _(u"Lluvia y Nieve Mezclada"),
  159.         "6": _(u"Lluvia y Aguanieve Mezclada"),
  160.         "7": _(u"Aguanieve"),
  161.         "8": _(u"Llovizna Helada"),
  162.         "9": _(u"Llovizna"),
  163.         "10": _(u"Lluvia Engelante"), # o lluvia helada
  164.         "11": _(u"Chaparrones"),
  165.         "12": _(u"Chaparrones"),
  166.         "13": _(u"Nieve Ligera"),
  167.         "14": _(u"Nieve Ligera"),
  168.         "15": _(u"Ventisca de Nieve"),
  169.         "16": _(u"Nieve"),
  170.         "17": _(u"Granizo"),
  171.         "18": _(u"Aguanieve"),
  172.         "19": _(u"Polvo"),
  173.         "20": _(u"Niebla"),
  174.         "21": _(u"Bruma"),
  175.         "22": _(u"Humo"),
  176.         "23": _(u"Tempestad"),
  177.         "24": _(u"Ventoso"),
  178.         "25": _(u"Fráo"),
  179.         "26": _(u"Muy Nublado"),
  180.         "27": _(u"Principalmente Nublado"),
  181.         "28": _(u"Principalmente Nublado"),
  182.         "29": _(u"Parcialmente Nublado"),
  183.         "30": _(u"Parcialmente Nublado"),
  184.         "31": _(u"Despejado"),
  185.         "32": _(u"Despejado"),
  186.         "33": _(u"Algo Nublado"),
  187.         "34": _(u"Algo Nublado"),
  188.         "35": _(u"Lluvia con Granizo"),
  189.         "36": _(u"Calor"),
  190.         "37": _(u"Tormentas Aisladas"),
  191.         "38": _(u"Tormentas Dispersas"),
  192.         "39": _(u"Tormentas Dispersas"),
  193.         "40": _(u"Chubascos Dispersos"),
  194.         "41": _(u"Nieve Pesada"),
  195.         "42": _(u"Nevadas Débiles y Dispersas"),
  196.         "43": _(u"Nevada Intensa"),
  197.         "44": _(u"Nubes Dispersas"),
  198.         "45": _(u"Tormentas"),
  199.         "46": _(u"Nevadas Dispersas"),
  200.         "47": _(u"Tormentas Aisladas"),
  201.         "na": _(u"N/A"),
  202.         "-": _(u"N/A")
  203.     }

  204.         conditions_text_fr = {
  205.         "0": _(u"Tornade"),
  206.         "1": _(u"Tempête Tropicale"),
  207.         "2": _(u"Ouragan"),
  208.         "3": _(u"Orages Violents"),
  209.         "4": _(u"Orageux"),
  210.         "5": _(u"Pluie et Neige"),
  211.         "6": _(u"Pluie et Neige Mouillée"),
  212.         "7": _(u"Variable avec averses"),
  213.         "8": _(u"Bruine Givrante"),
  214.         "9": _(u"Bruine"),
  215.         "10": _(u"Pluie Glacante"),
  216.         "11": _(u"Averses"),
  217.         "12": _(u"Averses"),
  218.         "13": _(u"Légère Neige"),
  219.         "14": _(u"Forte Neige"),
  220.         "15": _(u"Tempête de Neige"),
  221.         "16": _(u"Neige"),
  222.         "17": _(u"Grêle"),
  223.         "18": _(u"Pluie/Neige"),
  224.         "19": _(u"Nuage de poussière"),
  225.         "20": _(u"Brouillard"),
  226.         "21": _(u"Brume"),
  227.         "22": _(u"Fumée"),
  228.         "23": _(u"Tres Venteux"),
  229.         "24": _(u"Venteux"),
  230.         "25": _(u"Froid"),
  231.         "26": _(u"Nuageux"),
  232.         "27": _(u"Tres Nuageux"),
  233.         "28": _(u"Tres Nuageux"),
  234.         "29": _(u"Nuages Disséminés"),
  235.         "30": _(u"Nuages Disséminés"),
  236.         "31": _(u"Beau"),
  237.         "32": _(u"Beau"),
  238.         "33": _(u"Belles Éclaircies"),
  239.         "34": _(u"Belles Éclaircies"),
  240.         "35": _(u"Pluie avec Grêle"),
  241.         "36": _(u"Chaleur"),
  242.         "37": _(u"Orages Isolés"),
  243.         "38": _(u"Orages Localisés"),
  244.         "39": _(u"Orages Localisés"),
  245.         "40": _(u"Averses Localisées"),
  246.         "41": _(u"Neige Lourde"),
  247.         "42": _(u"Tempête de Neige Localisées"),
  248.         "43": _(u"Neige Lourde"),
  249.         "44": _(u"Nuages Disséminés"),
  250.         "45": _(u"Orages"),
  251.         "46": _(u"Tempête de Neige"),
  252.         "47": _(u"Orages Isolés"),
  253.         "na": _(u"N/A"),
  254.         "-": _(u"N/A")
  255.         }
  256.        
  257.         conditions_weather_font = {
  258.                 "0": _(u"W"),
  259.                 "1": _(u"V"),
  260.                 "2": _(u"W"),
  261.                 "3": _(u"s"),
  262.                 "4": _(u"p"),
  263.                 "5": _(u"k"),
  264.                 "6": _(u"k"),
  265.                 "7": _(u"g"),
  266.                 "8": _(u"g"),
  267.                 "9": _(u"g"),
  268.                 "10": _(u"h"),
  269.                 "11": _(u"g"),
  270.                 "12": _(u"g"),
  271.                 "13": _(u"k"),
  272.                 "14": _(u"k"),
  273.                 "15": _(u"k"),
  274.                 "16": _(u"k"),
  275.                 "17": _(u"k"),
  276.                 "18": _(u"k"),
  277.                 "19": _(u"e"),
  278.                 "20": _(u"e"),
  279.                 "21": _(u"a"),
  280.                 "22": _(u"d"),
  281.                 "23": _(u"d"),
  282.                 "24": _(u"d"),
  283.                 "25": _(u"d"),
  284.                 "26": _(u"e"),
  285.                 "27": _(u"e"),
  286.                 "28": _(u"e"),
  287.                 "29": _(u"c"),
  288.                 "30": _(u"c"),
  289.                 "31": _(u"a"),
  290.                 "32": _(u"a"),
  291.                 "33": _(u"b"),
  292.                 "34": _(u"b"),
  293.                 "35": _(u"k"),
  294.                 "36": _(u"a"),
  295.                 "37": _(u"f"),
  296.                 "38": _(u"f"),
  297.                 "39": _(u"f"),
  298.                 "40": _(u"g"),
  299.                 "41": _(u"k"),
  300.                 "42": _(u"k"),
  301.                 "43": _(u"k"),
  302.                 "44": _(u"b"),
  303.                 "45": _(u"g"),
  304.                 "46": _(u"k"),
  305.                 "47": _(u"f"),
  306.                 "na": _(u""),
  307.                 "-": _(u"")
  308.         }

  309.         conditions_moon_font = {
  310.                 "0": _(u"0"),
  311.                 "1": _(u"1"),
  312.                 "2": _(u"2"),
  313.                 "3": _(u"3"),
  314.                 "4": _(u"4"),
  315.                 "5": _(u"5"),
  316.                 "6": _(u"6"),
  317.                 "7": _(u"7"),
  318.                 "8": _(u"8"),
  319.                 "9": _(u"9"),
  320.                 "10": _(u"10"),
  321.                 "11": _(u"11"),
  322.                 "12": _(u"12"),
  323.                 "13": _(u"13"),
  324.                 "14": _(u"14"),
  325.                 "15": _(u"15"),
  326.                 "16": _(u"16"),
  327.                 "17": _(u"17"),
  328.                 "18": _(u"18"),
  329.                 "19": _(u"19"),
  330.                 "20": _(u"20"),
  331.                 "21": _(u"21"),
  332.                 "22": _(u"22"),
  333.                 "23": _(u"23"),
  334.                 "24": _(u"24"),
  335.                 "25": _(u"25"),
  336.                 "na": _(u""),
  337.                 "-": _(u"")
  338.         }
  339.                
  340.         day_of_week = {
  341.                 "Today": _(u"Today"),
  342.                 "Monday": _(u"Monday"),
  343.                 "Tuesday": _(u"Tuesday"),
  344.                 "Wednesday": _(u"Wednesday"),
  345.                 "Thursday": _(u"Thursday"),
  346.                 "Friday": _(u"Friday"),
  347.                 "Saturday": _(u"Saturday"),
  348.                 "Sunday": _(u"Sunday")
  349.         }

  350.         day_of_week_short = {
  351.                 "Today": _(u"Now"),
  352.                 "Monday": _(u"Mon"),
  353.                 "Tuesday": _(u"Tue"),
  354.                 "Wednesday": _(u"Wed"),
  355.                 "Thursday": _(u"Thu"),
  356.                 "Friday": _(u"Fri"),
  357.                 "Saturday": _(u"Sat"),
  358.                 "Sunday": _(u"Sun")
  359.         }

  360.         day_of_week_es = {
  361.                 "Today": _(u"hoy"),
  362.                 "Monday": _(u"lunes"),
  363.                 "Tuesday": _(u"martes"),
  364.                 "Wednesday": _(u"miércoles"),
  365.                 "Thursday": _(u"jueves"),
  366.                 "Friday": _(u"viernes"),
  367.                 "Saturday": _(u"sábado"),
  368.                 "Sunday": _(u"domingo")
  369.         }

  370.         day_of_week_short_es = {
  371.                 "Today": _(u"hoy"),
  372.                 "Monday": _(u"lun"),
  373.                 "Tuesday": _(u"mar"),
  374.                 "Wednesday": _(u"mié"),
  375.                 "Thursday": _(u"jue"),
  376.                 "Friday": _(u"vie"),
  377.                 "Saturday": _(u"sáb"),
  378.                 "Sunday": _(u"dom")
  379.         }

  380.         day_of_week_fr = {
  381.                 "Today": _(u"Aujourd'hui"),
  382.                 "Monday": _(u"Lundi"),
  383.                 "Tuesday": _(u"Mardi"),
  384.                 "Wednesday": _(u"Mercredi"),
  385.                 "Thursday": _(u"Jeudi"),
  386.                 "Friday": _(u"Vendredi"),
  387.                 "Saturday": _(u"Samedi"),
  388.                 "Sunday": _(u"Dimanche")
  389.         }

  390.         day_of_week_short_fr = {
  391.                 "Today": _(u"Auj"),
  392.                 "Monday": _(u"Lun"),
  393.                 "Tuesday": _(u"Mar"),
  394.                 "Wednesday": _(u"Mer"),
  395.                 "Thursday": _(u"Jeu"),
  396.                 "Friday": _(u"Ven"),
  397.                 "Saturday": _(u"Sam"),
  398.                 "Sunday": _(u"Dim")
  399.         }

  400.         bearing_arrow_font = {
  401.                 "N": _(u"a"),
  402.                 "NNE": _(u"b"),
  403.                 "NE": _(u"c"),
  404.                 "ENE": _(u"d"),
  405.                 "E": _(u"e"),
  406.                 "ESE": _(u"f"),
  407.                 "SE": _(u"g"),
  408.                 "SSE": _(u"h"),
  409.                 "S": _(u"i"),
  410.                 "SSW": _(u"j"),
  411.                 "SW": _(u"k"),
  412.                 "WSW": _(u"l"),
  413.                 "W": _(u"m"),
  414.                 "WNW": _(u"n"),
  415.                 "NW": _(u"o"),
  416.                 "NNW": _(u"p"),
  417.                 "N/A": _(u" ")
  418.         }

  419.         bearing_text_es = {
  420.                 "N": _(u"N"),
  421.                 "NNE": _(u"NNE"),
  422.                 "NE": _(u"NE"),
  423.                 "ENE": _(u"ENE"),
  424.                 "E": _(u"E"),
  425.                 "ESE": _(u"ESE"),
  426.                 "SE": _(u"SE"),
  427.                 "SSE": _(u"SSE"),
  428.                 "S": _(u"S"),
  429.                 "SSW": _(u"SSO"),
  430.                 "SW": _(u"SO"),
  431.                 "WSW": _(u"WOW"),
  432.                 "W": _(u"O"),
  433.                 "WNW": _(u"ONO"),
  434.                 "NW": _(u"NO"),
  435.                 "NNW": _(u"NNO"),
  436.                 "N/A": _(u"N\A")
  437.         }

  438.         bearing_text_fr = {
  439.                 "N": _(u"N"),
  440.                 "NNE": _(u"NNE"),
  441.                 "NE": _(u"NE"),
  442.                 "ENE": _(u"ENE"),
  443.                 "E": _(u"E"),
  444.                 "ESE": _(u"ESE"),
  445.                 "SE": _(u"SE"),
  446.                 "SSE": _(u"SSE"),
  447.                 "S": _(u"S"),
  448.                 "SSW": _(u"SSO"),
  449.                 "SW": _(u"SO"),
  450.                 "WSW": _(u"WOW"),
  451.                 "W": _(u"O"),
  452.                 "WNW": _(u"ONO"),
  453.                 "NW": _(u"NO"),
  454.                 "NNW": _(u"NNO"),
  455.                 "N/A": _(u"N\A")               
  456.         }
  457.                           
  458. class GlobalWeather:

  459.         current_conditions = []
  460.         day_forecast = []
  461.         night_forecast = []

  462.         locale = "en"

  463.         options = None
  464.         weatherxmldoc = ""

  465.         TEMP_FILEPATH_CURRENT = "/tmp/forecast-c-LOCATION.pkl"
  466.         TEMP_FILEPATH_DAYFORECAST = "/tmp/forecast-df-LOCATION.pkl"
  467.         TEMP_FILEPATH_NIGHTFORECAST = "/tmp/forecast-nf-LOCATION.pkl"
  468.         EXPIRY_MINUTES = 30
  469.         DEFAULT_SPACING = u" "
  470.                

  471.         def __init__(self,options):

  472.                 self.options = options
  473.                
  474.                 if self.options.locale == None:
  475.                         try:
  476.                                 self.locale = locale.getdefaultlocale()[0][0:2]
  477.                                 #self.locale = "es" #uncomment this line to force Spanish locale
  478.                                 #self.locale = "fr" #uncomment this line to force French locale                               
  479.                         except:
  480.                                 print "locale not set"
  481.                 else:
  482.                         self.locale = self.options.locale
  483.                         #self.locale = "es" #uncomment this line to force Spanish locale
  484.                         #self.locale = "fr" #uncomment this line to force French locale       

  485.                 if self.options.verbose == True:
  486.                         print >> sys.stdout, "locale set to ",self.locale

  487.         def getText(self,nodelist):
  488.                 rc = ""
  489.                 for node in nodelist:
  490.                         if node.nodeType == node.TEXT_NODE:
  491.                                 rc = rc + node.data
  492.                 return rc


  493.         def getSpaces(self,spaces):
  494.                 string = u""
  495.                 if spaces == None:
  496.                         string = self.DEFAULT_SPACING
  497.                 else:
  498.                         for i in range(0, spaces+1):
  499.                                 string = string + u" "
  500.                 return string


  501.         def isNumeric(self,string):
  502.                 try:
  503.                         dummy = float(string)
  504.                         return True
  505.                 except:
  506.                         return False

  507.         def isConnectionAvailable(self):
  508.                 # ensure we can access weather.com's server by opening the url
  509.                 try:
  510.                         usock = urllib2.urlopen('http://xoap.weather.com')
  511.                         usock.close()
  512.                         return True
  513.                 except:
  514.                         return False

  515.         def getBearingText(self,bearing):
  516.                 bearing = float(bearing)
  517.                 if bearing < 11.25:
  518.                         return u"N"
  519.                 elif bearing < 33.75:
  520.                         return u"NNE"
  521.                 elif bearing < 56.25:
  522.                         return u"NE"
  523.                 elif bearing < 78.75:
  524.                         return u"ENE"
  525.                 elif bearing < 101.25:
  526.                         return u"E"
  527.                 elif bearing < 123.75:
  528.                         return u"ESE"
  529.                 elif bearing < 146.25:
  530.                         return u"SE"
  531.                 elif bearing < 168.75:
  532.                         return u"SSE"
  533.                 elif bearing < 191.25:
  534.                         return u"S"
  535.                 elif bearing < 213.75:
  536.                         return u"SSW"
  537.                 elif bearing < 236.25:
  538.                         return u"SW"
  539.                 elif bearing < 258.75:
  540.                         return u"WSW"
  541.                 elif bearing < 281.25:
  542.                         return u"W"
  543.                 elif bearing < 303.75:
  544.                         return u"WNW"
  545.                 elif bearing < 326.25:
  546.                         return u"NW"
  547.                 elif bearing < 348.75:
  548.                         return u"NNW"
  549.                 else:
  550.                         return "N/A"

  551.         def convertCelsiusToFahrenheit(self,temp):
  552.                 return str(int(floor(((float(temp)*9.0)/5.0)+32)))

  553.         def convertKilometresToMiles(self,dist):
  554.                 return str(int(floor(float(dist)*0.621371192)))

  555.         def convertMillibarsToInches(self,mb):
  556.                 return str(int(floor(float(mb)/33.8582)))

  557.         def getTemplateList(self,template):

  558.                 templatelist = []
  559.        
  560.                 for template_part in template.split("{"):
  561.                         if template_part != "":
  562.                                 for template_part in template_part.split("}"):
  563.                                         if template_part != "":
  564.                                                 templatelist.append(u""+template_part)

  565.                 return templatelist


  566.         def getOutputText(self,datatype,startday,endday,night,shortweekday,imperial,hideunits,spaces):
  567.                 #try:
  568.                         output = u""
  569.                
  570.                         # define current units for output
  571.                         if hideunits == False:
  572.                                 if imperial == False:
  573.                                         tempunit = u"°C"
  574.                                         speedunit = u"kph"
  575.                                         pressureunit = u"mb"
  576.                                 else:
  577.                                         tempunit = u"°F"
  578.                                         speedunit = u"mph"
  579.                                         pressureunit = u"in"
  580.                         else:
  581.                                 tempunit = u"°"
  582.                                 speedunit = u""
  583.                                 pressureunit = u""

  584.                         if startday == None: # current conditions

  585.                                 if datatype == "DW":
  586.                                         if self.locale == "es":
  587.                                                 if shortweekday == True:
  588.                                                         output = WeatherText.day_of_week_short_es[self.current_conditions[0].day_of_week]
  589.                                                 else:
  590.                                                         output = WeatherText.day_of_week_es[self.current_conditions[0].day_of_week]
  591.                                         elif self.locale == "fr":
  592.                                                 if shortweekday == True:
  593.                                                         output = WeatherText.day_of_week_short_fr[self.current_conditions[0].day_of_week]
  594.                                                 else:
  595.                                                         output = WeatherText.day_of_week_fr[self.current_conditions[0].day_of_week]                                                       
  596.                                         else:
  597.                                                 if shortweekday == True:
  598.                                                         output = WeatherText.day_of_week_short[self.current_conditions[0].day_of_week]
  599.                                                 else:
  600.                                                         output = WeatherText.day_of_week[self.current_conditions[0].day_of_week]
  601.                                 elif datatype == "WF": # weather font
  602.                                         output = WeatherText.conditions_weather_font[self.current_conditions[0].condition_code]
  603.                                 elif datatype == "LT":
  604.                                         string = self.current_conditions[0].low
  605.                                         if self.isNumeric(string) == True:
  606.                                                 if imperial == True:
  607.                                                         string = self.convertCelsiusToFahrenheit(string)
  608.                                                 string = string + tempunit
  609.                                         output = string
  610.                                 elif datatype == "HT":
  611.                                         string = self.current_conditions[0].high
  612.                                         if self.isNumeric(string) == True:
  613.                                                 if imperial == True:
  614.                                                         string = self.convertCelsiusToFahrenheit(string)
  615.                                                 string = string + tempunit
  616.                                         output = string
  617.                                 elif datatype == "CC":
  618.                                         if self.locale == "es":
  619.                                                 output = WeatherText.conditions_text_es[self.current_conditions[0].condition_code]
  620.                                         elif self.locale == "fr":
  621.                                                 output = WeatherText.conditions_text_fr[self.current_conditions[0].condition_code]                                               
  622.                                         else:
  623.                                                 output = WeatherText.conditions_text[self.current_conditions[0].condition_code]
  624.                                 elif datatype == "CT":
  625.                                         output = self.current_conditions[0].condition_text
  626.                                 elif datatype == "PC":
  627.                                         string = self.current_conditions[0].precip
  628.                                         if self.isNumeric(string) == True:
  629.                                                 string = string + u"%"
  630.                                         output = string
  631.                                 elif datatype == "HM":
  632.                                         string = self.current_conditions[0].humidity
  633.                                         if self.isNumeric(string) == True:
  634.                                                 string = string + u"%"
  635.                                         output = string
  636.                                 elif datatype == "WD":
  637.                                         string = self.current_conditions[0].wind_dir
  638.                                         if self.isNumeric(string) == True:
  639.                                                 string = self.getBearingText(string)
  640.                                                
  641.                                         if self.locale == "es":
  642.                                                 output = WeatherText.bearing_text_es[string]
  643.                                         elif self.locale == "fr":
  644.                                                 output = WeatherText.bearing_text_fr[string]
  645.                                         else:
  646.                                                 output = string
  647.                                                                                        
  648.                                 elif datatype == "BF":
  649.                                         string = self.current_conditions[0].wind_dir
  650.                                         if self.isNumeric(string) == True:
  651.                                                 string = WeatherText.bearing_arrow_font[self.getBearingText(string)]
  652.                                         output = string                                       
  653.                                 elif datatype == "WS":
  654.                                         string = self.current_conditions[0].wind_speed
  655.                                         if self.isNumeric(string) == True:
  656.                                                 if imperial == True:
  657.                                                         string = self.convertKilometresToMiles(string)
  658.                                                 string = string + speedunit
  659.                                         output = string
  660.                                 elif datatype == "WG":
  661.                                         string = self.current_conditions[0].wind_gusts
  662.                                         if self.isNumeric(string) == True:
  663.                                                 if imperial == True:
  664.                                                         string = self.convertKilometresToMiles(string)
  665.                                                 string = string + speedunit
  666.                                         output = string
  667.                                 elif datatype == "CN":
  668.                                         output = self.current_conditions[0].city
  669.                                 elif datatype == "SR":
  670.                                         output = self.current_conditions[0].sunrise
  671.                                 elif datatype == "SS":
  672.                                         output = self.current_conditions[0].sunset
  673.                                 elif datatype == "MP":
  674.                                         output = self.current_conditions[0].moon_phase
  675.                                 elif datatype == "MF":
  676.                                         output = WeatherText.conditions_moon_font[self.current_conditions[0].moon_icon]                                                       
  677.                                 elif datatype == "BR":
  678.                                         string = self.current_conditions[0].bar_read
  679.                                         if self.isNumeric(string) == True:
  680.                                                 if imperial == True:
  681.                                                         string = self.convertMillibarsToInches(string)
  682.                                                 string = string + pressureunit
  683.                                         output = string
  684.                                 elif datatype == "BD":
  685.                                         output = self.current_conditions[0].bar_desc
  686.                                 else:
  687.                                         output = "\nERROR:Unknown data type requested"

  688.                         else: # forecast data

  689.                                 if endday == None: # if no endday was set use startday
  690.                                         endday = startday

  691.                                 if night == True: # night forecast required

  692.                                         for day_number in range(startday, endday+1):

  693.                                                 if datatype == "DW":
  694.                                                         if self.locale == "es":
  695.                                                                 if shortweekday == True:
  696.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_short_es[self.night_forecast[day_number].day_of_week]
  697.                                                                 else:
  698.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_es[self.night_forecast[day_number].day_of_week]
  699.                                                         elif self.locale == "fr":
  700.                                                                 if shortweekday == True:
  701.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_short_fr[self.night_forecast[day_number].day_of_week]
  702.                                                                 else:
  703.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_fr[self.night_forecast[day_number].day_of_week]
  704.                                                         else:
  705.                                                                 if shortweekday == True:
  706.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_short[self.night_forecast[day_number].day_of_week]
  707.                                                                 else:
  708.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week[self.night_forecast[day_number].day_of_week]
  709.                                                 elif datatype == "WF": # weather font
  710.                                                         output = output + self.getSpaces(spaces) + WeatherText.conditions_weather_font[self.night_forecast[day_number].condition_code]
  711.                                                 elif datatype == "LT":
  712.                                                         string = self.night_forecast[day_number].low
  713.                                                         if self.isNumeric(string) == True:
  714.                                                                 if imperial == True:
  715.                                                                         string = self.convertCelsiusToFahrenheit(string)
  716.                                                                 string = string + tempunit
  717.                                                         output = output + self.getSpaces(spaces) + string

  718.                                                 elif datatype == "HT":
  719.                                                         string = self.night_forecast[day_number].high
  720.                                                         if self.isNumeric(string) == True:
  721.                                                                 if imperial == True:
  722.                                                                         string = self.convertCelsiusToFahrenheit(string)
  723.                                                                 string = string + tempunit
  724.                                                         output = output + self.getSpaces(spaces) + string
  725.                                                 elif datatype == "CC":
  726.                                                         if self.locale == "es":
  727.                                                                 output = output + self.getSpaces(spaces) + WeatherText.conditions_text_es[self.night_forecast[day_number].condition_code]
  728.                                                         elif self.locale == "fr":
  729.                                                                 output = output + self.getSpaces(spaces) + WeatherText.conditions_text_fr[self.night_forecast[day_number].condition_code]
  730.                                                         else:
  731.                                                                 output = output + self.getSpaces(spaces) + WeatherText.conditions_text[self.night_forecast[day_number].condition_code]
  732.                                                 elif datatype == "CT":
  733.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].condition_text
  734.                                                 elif datatype == "PC":
  735.                                                         string = self.night_forecast[day_number].precip
  736.                                                         if self.isNumeric(string) == True:
  737.                                                                 string = string + u"%"
  738.                                                         output = output + self.getSpaces(spaces) + string
  739.                                                 elif datatype == "HM":
  740.                                                         string = self.night_forecast[day_number].humidity
  741.                                                         if self.isNumeric(string) == True:
  742.                                                                 string = string + u"%"
  743.                                                         output = output + self.getSpaces(spaces) + string
  744.                                                 elif datatype == "WD":
  745.                                                         string = self.night_forecast[day_number].wind_dir
  746.                                                         if self.locale == "es":
  747.                                                                 output = output + self.getSpaces(spaces) + WeatherText.bearing_text_es[string]
  748.                                                         elif self.locale == "fr":
  749.                                                                 output = output + self.getSpaces(spaces) + WeatherText.bearing_text_fr[string]
  750.                                                         else:
  751.                                                                 output = output + self.getSpaces(spaces) + string
  752.                            
  753.                                                 elif datatype == "BF":
  754.                                                         output = output + self.getSpaces(spaces) + WeatherText.bearing_arrow_font[self.night_forecast[day_number].wind_dir]
  755.                                                 elif datatype == "WS":
  756.                                                         string = self.night_forecast[day_number].wind_speed
  757.                                                         if self.isNumeric(string) == True:
  758.                                                                 if imperial == True:
  759.                                                                         string = self.convertKilometresToMiles(string)
  760.                                                                 string = string + speedunit
  761.                                                         output = output + self.getSpaces(spaces) + string
  762.                                                 elif datatype == "WG":
  763.                                                         string = self.night_forecast[day_number].wind_gusts
  764.                                                         if self.isNumeric(string) == True:
  765.                                                                 if imperial == True:
  766.                                                                         string = self.convertKilometresToMiles(string)
  767.                                                                 string = string + speedunit
  768.                                                         output = output + self.getSpaces(spaces) + string
  769.                                                 elif datatype == "CN":
  770.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].city
  771.                                                 elif datatype == "SR":
  772.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].sunrise
  773.                                                 elif datatype == "SS":
  774.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].sunset
  775.                                                 elif datatype == "MP":
  776.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].moon_phase
  777.                                                 elif datatype == "MF":
  778.                                                         output = output + self.getSpaces(spaces) + WeatherText.conditions_moon_font[self.night_forecast[day_number].moon_icon]
  779.                                                 elif datatype == "BR":
  780.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].bar_read
  781.                                                 elif datatype == "BD":
  782.                                                         output = output + self.getSpaces(spaces) + self.night_forecast[day_number].bar_desc
  783.                                                 else:
  784.                                                         output = "\nERROR:Unknown data type requested"
  785.                                                         break

  786.                                 else: # day forecast wanted

  787.                                         for day_number in range(startday, endday+1):

  788.                                                 if datatype == "DW":
  789.                                                         if self.locale == "es":
  790.                                                                 if shortweekday == True:
  791.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_short_es[self.day_forecast[day_number].day_of_week]
  792.                                                                 else:
  793.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_es[self.day_forecast[day_number].day_of_week]
  794.                                                         elif self.locale == "fr":
  795.                                                                 if shortweekday == True:
  796.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_short_fr[self.day_forecast[day_number].day_of_week]
  797.                                                                 else:
  798.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_fr[self.day_forecast[day_number].day_of_week]                                                                       
  799.                                                         else:
  800.                                                                 if shortweekday == True:
  801.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week_short[self.day_forecast[day_number].day_of_week]
  802.                                                                 else:
  803.                                                                         output = output + self.getSpaces(spaces) + WeatherText.day_of_week[self.day_forecast[day_number].day_of_week]
  804.                                                 elif datatype == "WF": # weather font
  805.                                                         output = output + self.getSpaces(spaces) + WeatherText.conditions_weather_font[self.day_forecast[day_number].condition_code]
  806.                                                 elif datatype == "LT":
  807.                                                         string = self.day_forecast[day_number].low
  808.                                                         if self.isNumeric(string) == True:
  809.                                                                 if imperial == True:
  810.                                                                         string = self.convertCelsiusToFahrenheit(string)
  811.                                                                 string = string + tempunit
  812.                                                         output = output + self.getSpaces(spaces) + string
  813.                                                 elif datatype == "HT":
  814.                                                         string = self.day_forecast[day_number].high
  815.                                                         if self.isNumeric(string) == True:
  816.                                                                 if imperial == True:
  817.                                                                         string = self.convertCelsiusToFahrenheit(string)
  818.                                                                 string = string + tempunit
  819.                                                         output = output + self.getSpaces(spaces) + string
  820.                                                 elif datatype == "CC":
  821.                                                         if self.locale == "es":
  822.                                                                 output = output + self.getSpaces(spaces) + WeatherText.conditions_text_es[self.day_forecast[day_number].condition_code]
  823.                                                         elif self.locale == "fr":
  824.                                                                 output = output + self.getSpaces(spaces) + WeatherText.conditions_text_fr[self.day_forecast[day_number].condition_code]
  825.                                                         else:
  826.                                                                 output = output + self.getSpaces(spaces) + WeatherText.conditions_text[self.day_forecast[day_number].condition_code]
  827.                                                 elif datatype == "CT":
  828.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].condition_text
  829.                                                 elif datatype == "PC":
  830.                                                         string = self.day_forecast[day_number].precip
  831.                                                         if self.isNumeric(string) == True:
  832.                                                                 string = string + u"%"
  833.                                                         output = output + self.getSpaces(spaces) + string
  834.                                                 elif datatype == "HM":
  835.                                                         string = self.day_forecast[day_number].humidity
  836.                                                         if self.isNumeric(string) == True:
  837.                                                                 string = string + u"%"
  838.                                                         output = output + self.getSpaces(spaces) + string
  839.                                                 elif datatype == "WD":
  840.                                                         string = self.day_forecast[day_number].wind_dir
  841.                                                        
  842.                                                         if self.locale == "es":
  843.                                                                 output = output + self.getSpaces(spaces) + WeatherText.bearing_text_es[string]
  844.                                                         elif self.locale == "fr":
  845.                                                                 output = output + self.getSpaces(spaces) + WeatherText.bearing_text_fr[string]
  846.                                                         else:
  847.                                                                 output = output + self.getSpaces(spaces) + string       

  848.                                                 elif datatype == "BF":
  849.                                                         output = output + self.getSpaces(spaces) + WeatherText.bearing_arrow_font[self.day_forecast[day_number].wind_dir]
  850.                                                 elif datatype == "WS":
  851.                                                         string = self.day_forecast[day_number].wind_speed
  852.                                                         if self.isNumeric(string) == True:
  853.                                                                 if imperial == True:
  854.                                                                         string = self.convertKilometresToMiles(string)
  855.                                                                 string = string + speedunit
  856.                                                         output = output + self.getSpaces(spaces) + string
  857.                                                 elif datatype == "WG":
  858.                                                         string = self.day_forecast[day_number].wind_gusts
  859.                                                         if self.isNumeric(string) == True:
  860.                                                                 if imperial == True:
  861.                                                                         string = self.convertKilometresToMiles(string)
  862.                                                                 string = string + speedunit
  863.                                                         output = output + self.getSpaces(spaces) + string
  864.                                                 elif datatype == "CN":
  865.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].city
  866.                                                 elif datatype == "SR":
  867.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].sunrise
  868.                                                 elif datatype == "SS":
  869.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].sunset
  870.                                                 elif datatype == "MP":
  871.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].moon_phase
  872.                                                 elif datatype == "MF":
  873.                                                         output = output + self.getSpaces(spaces) + WeatherText.conditions_moon_font[self.day_forecast[day_number].moon_icon]
  874.                                                 elif datatype == "BR":
  875.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].bar_read
  876.                                                 elif datatype == "BD":
  877.                                                         output = output + self.getSpaces(spaces) + self.day_forecast[day_number].bar_desc
  878.                                                 else:
  879.                                                         output = u"\nERROR:Unknown data type requested"
  880.                                                         break

  881.                         output = u""+output.strip(u" ") # lose leading/trailing spaces
  882.                         return output

  883.                 #except:
  884.                         #print "getOutputText:Unexpected error: ", sys.exc_info()[0]


  885.         def getOutputTextFromTemplate(self,template):
  886.                 #try:

  887.                         # keys to template data
  888.                         DATATYPE_KEY = "--datatype="
  889.                         STARTDAY_KEY = "--startday="
  890.                         ENDDAY_KEY = "--endday="
  891.                         NIGHT_KEY = "--night"
  892.                         SHORTWEEKDAY_KEY = "--shortweekday"
  893.                         IMPERIAL_KEY = "--imperial"
  894.                         HIDEUNITS_KEY = "--hideunits"
  895.                         SPACES_KEY = "--spaces="

  896.                         output = u""

  897.                         optionfound = False

  898.                         #load the file
  899.                         try:
  900.                                 fileinput = open(self.options.template)
  901.                                 template = fileinput.read()
  902.                                 fileinput.close()
  903.                         except:
  904.                                 output = u"Template file no found!"

  905.                         templatelist = self.getTemplateList(template)

  906.                         # lets walk through the template list and determine the output for each item found
  907.                         for i in range(0,len(templatelist)-1):

  908.                                 pos = templatelist[i].find(DATATYPE_KEY)
  909.                                 if pos != -1:
  910.                                         optionfound = True
  911.                                         pos = pos + len(DATATYPE_KEY)
  912.                                         datatype = templatelist[i][pos:pos+4].strip("}").strip("{").strip("-").strip(" ")
  913.                                 else:
  914.                                         datatype = None

  915.                                 pos = templatelist[i].find(STARTDAY_KEY)
  916.                                 if pos != -1:
  917.                                         optionfound = True
  918.                                         pos = pos + len(STARTDAY_KEY)
  919.                                         startday = int(templatelist[i][pos:pos+4].strip("}").strip("{").strip("-").strip(" "))
  920.                                 else:
  921.                                         startday = None

  922.                                 pos = templatelist[i].find(ENDDAY_KEY)
  923.                                 if pos != -1:
  924.                                         optionfound = True
  925.                                         pos = pos + len(ENDDAY_KEY)
  926.                                         endday = int(templatelist[i][pos:pos+4].strip("}").strip("{").strip("-").strip(" "))
  927.                                 else:
  928.                                         endday = None

  929.                                 pos = templatelist[i].find(NIGHT_KEY)
  930.                                 if pos != -1:
  931.                                         optionfound = True
  932.                                         night = True
  933.                                 else:
  934.                                         night = False

  935.                                 pos = templatelist[i].find(SHORTWEEKDAY_KEY)
  936.                                 if pos != -1:
  937.                                         optionfound = True
  938.                                         shortweekday = True
  939.                                 else:
  940.                                         shortweekday = False

  941.                                 pos = templatelist[i].find(IMPERIAL_KEY)
  942.                                 if pos != -1:
  943.                                         optionfound = True
  944.                                         imperial = True
  945.                                 else:
  946.                                         imperial = False

  947.                                 pos = templatelist[i].find(HIDEUNITS_KEY)
  948.                                 if pos != -1:
  949.                                         optionfound = True
  950.                                         hideunits = True
  951.                                 else:
  952.                                         hideunits = False

  953.                                 pos = templatelist[i].find(SPACES_KEY)
  954.                                 if pos != -1:
  955.                                         optionfound = True
  956.                                         pos = pos + len(SPACES_KEY)
  957.                                         spaces = int(templatelist[i][pos:pos+4].strip("}").strip("{").strip("-").strip(" "))
  958.                                 else:
  959.                                         spaces = 1

  960.                                 if optionfound == True:
  961.                                         templatelist[i] = self.getOutputText(datatype,startday,endday,night,shortweekday,imperial,hideunits,spaces)
  962.                                         optionfound = False

  963.                         # go through the list concatenating the output now that it's been populated
  964.                         for item in templatelist:
  965.                                 output = output + item

  966.                         return output

  967.                 #except:
  968.                         #print "getOutputTextFromTemplate:Unexpected error: ", sys.exc_info()[0]


  969.         def fetchData(self):

  970.                 # always fetch metric data, use conversation functions on this data
  971.                 file_path_current = self.TEMP_FILEPATH_CURRENT.replace("LOCATION",self.options.location)
  972.                 file_path_dayforecast = self.TEMP_FILEPATH_DAYFORECAST.replace("LOCATION",self.options.location)
  973.                 file_path_nightforecast = self.TEMP_FILEPATH_NIGHTFORECAST.replace("LOCATION",self.options.location)

  974.                 if self.isConnectionAvailable() == False:
  975.                         if os.path.exists(file_path_current):
  976.                                 RefetchData = False
  977.                         else: # no connection, no cache, bang!
  978.                                 print "No internet connection is available and no cached weather data exists."
  979.                 elif self.options.refetch == True:
  980.                         RefetchData = True
  981.                 else:
  982.                          # does the data need retrieving again?
  983.                          if os.path.exists(file_path_current):
  984.                                  lastmodDate = time.localtime(os.stat(file_path_current)[ST_MTIME])
  985.                                 expiryDate = (datetime.datetime.today() - datetime.timedelta(minutes=self.EXPIRY_MINUTES)).timetuple()

  986.                                 if expiryDate > lastmodDate:
  987.                                         RefetchData = True
  988.                                 else:
  989.                                         RefetchData = False
  990.                         else:
  991.                                 RefetchData = True


  992.                 # fetch the current conditions data, either from the website or by 'unpickling'
  993.                 if RefetchData == True:

  994.                         # obtain current conditions data from xoap service
  995.                         try:

  996.                                 # http://xoap.weather.com/weather/local/UKXX0103?cc=*&dayf=5&link=xoap&prod=xoap&par=1061785028&key=e374effbfd74930b

  997.                                 url = 'http://xoap.weather.com/weather/local/' + self.options.location + '?cc=*&dayf=8&link=xoap&prod=xoap&par=1061785028&key=e374effbfd74930b&unit=m'
  998.                                 if self.options.verbose == True:
  999.                                         print >> sys.stdout, "fetching weather data from ",url

  1000.                                 usock = urllib2.urlopen(url)
  1001.                                 xml = usock.read()
  1002.                                 usock.close()
  1003.                                 self.weatherxmldoc = minidom.parseString(xml)
  1004.                         except:
  1005.                                 print "fetchData:Unexpected error: ", sys.exc_info()[0]
  1006.                                 print "Unable to contact weather source for current conditions"

  1007.                         # tell the user if the location is bad...
  1008.                         found = xml.find("Invalid location provided")
  1009.                         if found != -1:
  1010.                                 print "Invalid location provided"

  1011.                         # interrogate weather data, load into class structure and pickle it
  1012.                         try:

  1013.                                 # prepare weather data lists
  1014.                                 self.current_conditions = []
  1015.                                 self.day_forecast = []
  1016.                                 self.night_forecast = []

  1017.                                 # collect general data
  1018.                                 weather_n = self.weatherxmldoc.documentElement
  1019.                                 location_n = weather_n.getElementsByTagName('loc')[0]
  1020.                                 city_n = location_n.getElementsByTagName('dnam')[0]
  1021.                                 city = self.getText(city_n.childNodes)

  1022.                                 # collect current conditions data
  1023.                                 day_of_week = u"Today"
  1024.                                 precip = u"N/A"
  1025.                                 sunrise_n = location_n.getElementsByTagName('sunr')[0]
  1026.                                 sunrise = self.getText(sunrise_n.childNodes)
  1027.                                 sunset_n = location_n.getElementsByTagName('suns')[0]
  1028.                                 sunset = self.getText(sunset_n.childNodes)
  1029.                                 current_condition_n = weather_n.getElementsByTagName('cc')[0]
  1030.                                 current_desc_n = current_condition_n.getElementsByTagName('t')[0]
  1031.                                 current_desc = self.getText(current_desc_n.childNodes)
  1032.                                 current_code_n = current_condition_n.getElementsByTagName('icon')[0]
  1033.                                 current_code = self.getText(current_code_n.childNodes)
  1034.                                 current_temp_n = current_condition_n.getElementsByTagName('tmp')[0]
  1035.                                 current_temp = self.getText(current_temp_n.childNodes)
  1036.                                 current_temp_feels_n = current_condition_n.getElementsByTagName('flik')[0]
  1037.                                 current_temp_feels = self.getText(current_temp_feels_n.childNodes)
  1038.                                 bar_n = current_condition_n.getElementsByTagName('bar')[0]
  1039.                                 bar_read_n = bar_n.getElementsByTagName('r')[0]
  1040.                                 bar_read = self.getText(bar_read_n.childNodes)
  1041.                                 bar_desc_n = bar_n.getElementsByTagName('d')[0]
  1042.                                 bar_desc = self.getText(bar_desc_n.childNodes)
  1043.                                 wind_n = current_condition_n.getElementsByTagName('wind')[0]
  1044.                                 wind_speed_n = wind_n.getElementsByTagName('s')[0]
  1045.                                 wind_speed = self.getText(wind_speed_n.childNodes)
  1046.                                 wind_gust_n = wind_n.getElementsByTagName('gust')[0]
  1047.                                 wind_gusts = self.getText(wind_gust_n.childNodes)
  1048.                                 wind_dir_n = wind_n.getElementsByTagName('d')[0]
  1049.                                 wind_direction = self.getText(wind_dir_n.childNodes)
  1050.                                 humidity_n = current_condition_n.getElementsByTagName('hmid')[0]
  1051.                                 humidity = self.getText(humidity_n.childNodes)
  1052.                                 moon_n = current_condition_n.getElementsByTagName('moon')[0]
  1053.                                 moon_icon_n = moon_n.getElementsByTagName('icon')[0]
  1054.                                 moon_icon = self.getText(moon_icon_n.childNodes)
  1055.                                 moon_phase_n = moon_n.getElementsByTagName('t')[0]
  1056.                                 moon_phase = self.getText(moon_phase_n.childNodes)
  1057.                                 current_conditions_data = WeatherData(day_of_week, current_temp, current_temp, current_code, current_desc, precip, humidity, wind_direction, wind_speed, wind_gusts, city, sunrise, sunset, moon_phase, moon_icon, bar_read, bar_desc)
  1058.                                 self.current_conditions.append(current_conditions_data)

  1059.                                 # collect forecast data
  1060.                                 bar_read = u"N/A"
  1061.                                 bar_desc = u"N/A"
  1062.                                 moon_phase = u"N/A"
  1063.                                 moon_icon = u"na"
  1064.                                 forecast_n = weather_n.getElementsByTagName('dayf')[0]
  1065.                                 day_nodes = forecast_n.getElementsByTagName('day')
  1066.        
  1067.                                 for day in day_nodes:
  1068.                                         day_of_week = day.getAttribute('t')
  1069.                                         day_of_year = day.getAttribute('dt')
  1070.                                         high_temp_n = day.getElementsByTagName('hi')[0]
  1071.                                         high_temp = self.getText(high_temp_n.childNodes)
  1072.                                         low_temp_n = day.getElementsByTagName('low')[0]
  1073.                                         low_temp = self.getText(low_temp_n.childNodes)

  1074.                                         sunrise_n = day.getElementsByTagName('sunr')[0]
  1075.                                         sunrise = self.getText(sunrise_n.childNodes)
  1076.                                         sunset_n = day.getElementsByTagName('suns')[0]
  1077.                                         sunset = self.getText(sunset_n.childNodes)

  1078.                                         # day forecast specific data
  1079.                                         daytime_n = day.getElementsByTagName('part')[0] # day
  1080.                                         condition_code_n = daytime_n.getElementsByTagName('icon')[0]
  1081.                                         condition_code = self.getText(condition_code_n.childNodes)
  1082.                                         condition_n = daytime_n.getElementsByTagName('t')[0]
  1083.                                         condition = self.getText(condition_n.childNodes)
  1084.                                         precip_n = daytime_n.getElementsByTagName('ppcp')[0]
  1085.                                         precip = self.getText(precip_n.childNodes)
  1086.                                         humidity_n = daytime_n.getElementsByTagName('hmid')[0]
  1087.                                         humidity = self.getText(humidity_n.childNodes)
  1088.                                         wind_n = daytime_n.getElementsByTagName('wind')[0]
  1089.                                         wind_speed_n = wind_n.getElementsByTagName('s')[0]
  1090.                                         wind_speed = self.getText(wind_speed_n.childNodes)
  1091.                                         wind_direction_n = wind_n.getElementsByTagName('t')[0]
  1092.                                         wind_direction = self.getText(wind_direction_n.childNodes)
  1093.                                         wind_gusts_n = wind_n.getElementsByTagName('gust')[0]
  1094.                                         wind_gusts = self.getText(wind_gusts_n.childNodes)
  1095.                                         day_forecast_data = WeatherData(day_of_week, low_temp, high_temp, condition_code, condition, precip, humidity, wind_direction, wind_speed, wind_gusts, city, sunrise, sunset, moon_phase, moon_icon, bar_read, bar_desc)
  1096.                                         self.day_forecast.append(day_forecast_data)        

  1097.                                         # night forecast specific data
  1098.                                         daytime_n = day.getElementsByTagName('part')[1] # night
  1099.                                         condition_code_n = daytime_n.getElementsByTagName('icon')[0]
  1100.                                         condition_code = self.getText(condition_code_n.childNodes)
  1101.                                         condition_n = daytime_n.getElementsByTagName('t')[0]
  1102.                                         condition = self.getText(condition_n.childNodes)
  1103.                                         precip_n = daytime_n.getElementsByTagName('ppcp')[0]
  1104.                                         precip = self.getText(precip_n.childNodes)
  1105.                                         humidity_n = daytime_n.getElementsByTagName('hmid')[0]
  1106.                                         humidity = self.getText(humidity_n.childNodes)
  1107.                                         wind_n = daytime_n.getElementsByTagName('wind')[0]
  1108.                                         wind_speed_n = wind_n.getElementsByTagName('s')[0]
  1109.                                         wind_speed = self.getText(wind_speed_n.childNodes)
  1110.                                         wind_direction_n = wind_n.getElementsByTagName('t')[0]
  1111.                                         wind_direction = self.getText(wind_direction_n.childNodes)
  1112.                                         wind_gusts_n = wind_n.getElementsByTagName('gust')[0]
  1113.                                         wind_gusts = self.getText(wind_gusts_n.childNodes)
  1114.                                         night_forecast_data = WeatherData(day_of_week, low_temp, high_temp, condition_code, condition, precip, humidity, wind_direction, wind_speed, wind_gusts, city, sunrise, sunset, moon_phase, moon_icon, bar_read, bar_desc)
  1115.                                         self.night_forecast.append(night_forecast_data)


  1116.                                 # pickle the data for next time!
  1117.                                 fileoutput = open(file_path_current, 'w')
  1118.                                 pickle.dump(self.current_conditions,fileoutput)
  1119.                                  fileoutput.close()

  1120.                                 fileoutput = open(file_path_dayforecast, 'w')
  1121.                                 pickle.dump(self.day_forecast,fileoutput)
  1122.                                  fileoutput.close()

  1123.                                 fileoutput = open(file_path_nightforecast, 'w')
  1124.                                 pickle.dump(self.night_forecast,fileoutput)
  1125.                                  fileoutput.close()
  1126.                
  1127.                         except:
  1128.                                 print "fetchData:Unexpected error: ", sys.exc_info()[0]
  1129.                                 print "Unable to interrogate the weather data"

  1130.                 else: # fetch weather data from pickled class files
  1131.                         if self.options.verbose == True:
  1132.                                 print >> sys.stdout, "fetching weather data from file: ",file_path_current

  1133.                         fileinput = open(file_path_current, 'r')
  1134.                         self.current_conditions = pickle.load(fileinput)
  1135.                         fileinput.close()

  1136.                         if self.options.verbose == True:
  1137.                                 print >> sys.stdout, "fetching day forecast data from files: ",file_path_dayforecast, file_path_nightforecast

  1138.                         fileinput = open(file_path_dayforecast, 'r')
  1139.                         self.day_forecast = pickle.load(fileinput)
  1140.                         fileinput.close()

  1141.                         if self.options.verbose == True:
  1142.                                 print >> sys.stdout, "fetching day forecast data from files: ",file_path_nightforecast, file_path_nightforecast

  1143.                         fileinput = open(file_path_nightforecast, 'r')
  1144.                         self.night_forecast = pickle.load(fileinput)
  1145.                         fileinput.close()

  1146.         def outputData(self):
  1147.                 #try:

  1148.                         if self.options.template != None:

  1149.                                 output = self.getOutputTextFromTemplate(self.options.template)

  1150.                         else:

  1151.                                 output = self.getOutputText(self.options.datatype,self.options.startday,self.options.endday,self.options.night,self.options.shortweekday,self.options.imperial,self.options.hideunits,self.options.spaces)


  1152.                         print output.encode("utf-8")

  1153.                 #except:
  1154.                         #print "outputData:Unexpected error: ", sys.exc_info()[0]

  1155. if __name__ == "__main__":

  1156.         parser = CommandLineParser()
  1157.         (options, args) = parser.parse_args()

  1158.         if options.verbose == True:
  1159.                 print >> sys.stdout, "location:",options.location
  1160.                 print >> sys.stdout, "imperial:",options.imperial
  1161.                 print >> sys.stdout, "datatype:",options.datatype
  1162.                 print >> sys.stdout, "night:",options.night
  1163.                 print >> sys.stdout, "start day:",options.startday
  1164.                 print >> sys.stdout, "end day:",options.endday
  1165.                 print >> sys.stdout, "spaces:",options.spaces
  1166.                 print >> sys.stdout, "verbose:",options.verbose
  1167.                 print >> sys.stdout, "refetch:",options.refetch

  1168.         # create new global weather object
  1169.         weather = GlobalWeather(options)
  1170.         weather.fetchData()
  1171.         weather.outputData()
复制代码
回复 支持 反对

使用道具 举报

发表于 2009-5-6 17:52:54 | 显示全部楼层
好花。好乱。不舒服。
回复 支持 反对

使用道具 举报

发表于 2009-5-6 19:18:36 | 显示全部楼层
太乱了…… 看着头疼,还弄些瘟到死效果…… 残念……
回复 支持 反对

使用道具 举报

发表于 2009-5-8 00:04:56 | 显示全部楼层
太花了,这种桌面,估计平时都是最大化程序吧?
长期看着,可要精神紊乱的
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表