Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cliweather 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #!/usr/bin/env python2
  2. from xml.dom.minidom import parseString
  3. try:
  4. from urllib.request import urlopen
  5. except ImportError:
  6. from urllib import urlopen
  7. try:
  8. from urllib.parse import urlencode
  9. except ImportError:
  10. from urllib import urlencode
  11. from sys import argv, exit, stderr, stdout
  12. import os.path
  13. import datetime
  14. VERSION = '.01'
  15. URL = 'http://www.aaronfoltz.com'
  16. YAHOO_API_KEY = 'dj0yJmk9TEdTT09FNVp6MWlhJmQ9WVdrOVpsaGhVbEZTTmpJbWNHbzlOalUyT0RNMk1qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTkw'
  17. WOEID_URL = 'http://where.yahooapis.com/v1/places.q({0})?'
  18. YAHOO_API_URL = 'http://weather.yahooapis.com/forecastrss?'
  19. def main():
  20. try:
  21. # Forecast option
  22. if "-f" in argv[1]:
  23. # See if there is a zip with the argument
  24. try:
  25. place = argv[2]
  26. getForecast(place)
  27. # If no zip is provided, get it from the geolocation service
  28. except IndexError:
  29. place = getPlace()
  30. getForecast(place)
  31. # Else there isn't an option there, it must be a zip code if anything
  32. else:
  33. try:
  34. place = argv[1]
  35. getCurrent(place)
  36. # No arguments are provided, get the place from the geolocation service
  37. except IndexError:
  38. place = getPlace()
  39. getCurrent(place)
  40. except IndexError:
  41. place = getPlace()
  42. getCurrent(place)
  43. def getCurrent(place):
  44. woeid = getWOEID(place)
  45. # Call to get the weather
  46. api = YAHOO_API_URL + urlencode({'w': woeid})
  47. dom = parseString(urlopen(api).read())
  48. # Get the necessary DOM elements
  49. location = dom.getElementsByTagName('yweather:location')[0]
  50. currentConditions = dom.getElementsByTagName('yweather:condition')[0]
  51. atmosphere = dom.getElementsByTagName('yweather:atmosphere')[0]
  52. wind = dom.getElementsByTagName('yweather:wind')[0]
  53. print
  54. print('Location: %s, %s' % (location.getAttribute("city"), location.getAttribute("region")))
  55. print('Condition: %s' % currentConditions.getAttribute("text"))
  56. print('Temperature: %sF/%sC' % (currentConditions.getAttribute("temp"), fahToCel(currentConditions.getAttribute("temp"))))
  57. print('Humidity: %s' % atmosphere.getAttribute('humidity') + "%")
  58. print('Wind: %s mph %s' % (wind.getAttribute("speed"), degToCompass(wind.getAttribute("direction"))))
  59. def getForecast(place):
  60. woeid = getWOEID(place)
  61. # Call to get the weather
  62. api = YAHOO_API_URL + urlencode({'w': woeid})
  63. dom = parseString(urlopen(api).read())
  64. # Get the necessary DOM elements
  65. forecasts = dom.getElementsByTagName('yweather:forecast')
  66. print
  67. # Print info for each forecast day
  68. for day in forecasts:
  69. print('Day: %s' % datetime.datetime.strptime(day.getAttribute('date'), '%d %b %Y').strftime('%A, %B %d, %Y'))
  70. print('\tHigh: %sF/%sC' % (day.getAttribute("high"), fahToCel(day.getAttribute("high"))))
  71. print('\tLow: %sF/%sC' % (day.getAttribute("low"), fahToCel(day.getAttribute("low"))))
  72. print('\tCondition: %s' % day.getAttribute('text'))
  73. # Retrives zip code if not entered
  74. def getPlace():
  75. import re
  76. path = "%s/.cliweather" % os.getenv("HOME")
  77. if os.path.exists(path):
  78. try:
  79. f = open(path, 'r')
  80. return f.read()
  81. except:
  82. print "Could not load .cliweather"
  83. # Get the geoip information
  84. geoip = urlopen('http://api.ipinfodb.com/v3/ip-city/?key=29e619f84fd83f32c4987573a4ccc11fd59b268234aa50c1289230f1fff0dbd2').read()
  85. # The returned value is perfectly fine
  86. if re.match("OK;;", geoip):
  87. # regex to get the zip code
  88. expression = "OK;;([^;]+;){5}(\w+)"
  89. result = re.search(expression, geoip)
  90. # return the zip code from the returned data
  91. return result.group(2)
  92. # Make a call to Yahoo's API to get the WOEID given a zip code
  93. def getWOEID(place):
  94. # Make the call to the API to return the XML with WOEID
  95. api = (WOEID_URL + urlencode({'appid': YAHOO_API_KEY})).format(place)
  96. dom = parseString(urlopen(api).read())
  97. # Return parsed WOEID
  98. return dom.getElementsByTagName('woeid')[0].firstChild.data
  99. # Convert Fah to Cel
  100. def fahToCel(value):
  101. return '{0:.0f}'.format((100.0/(212-32)) * (int(value) - 32))
  102. # From http://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
  103. def degToCompass(num):
  104. num = int(num)
  105. val=int((num / 22.5) + .5)
  106. arr=["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
  107. return arr[(val % 16)]
  108. if __name__ == "__main__":
  109. main()