Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # @author Shinmera
- # @pyver 3.x
- import json
- import urllib.request
- import time
- import sys
- import re
- import argparse
- def coordinates(degree, minute, second):
- return degree + minute/60 + second/3600
- timestamp = time.time()
- apikey = "00000000000000000000000000000000"
- latitude = coordinates(22, 16, 42)
- longitude = coordinates(114, 9, 32)
- homeFile = r"\\psf\Home\Documents\AHK Scripts\weather\curr.txt"
- forecastIOAddress = "https://api.forecast.io/forecast/{0}/{1},{2}?units=si&exclude=hourly,daily,flags".format(apikey, latitude, longitude, timestamp)
- HKOAddress = ("http://www.hko.gov.hk/textonly/forecast/englishwx2.htm", "http://www.hko.gov.hk/wxinfo/ts/text_readings_e.htm")
- destPlace = r"\\psf\Home\Documents\AHK Scripts\weather\local.htm"
- weatherData = {};
- ## Code below
- cmdparse = argparse.ArgumentParser()
- cmdparse.add_argument("source", choices=["hko", "fio"])
- cmdparse.add_argument("-v", "--verbose", action="store_true", dest="verbose")
- cmdparse.add_argument("-n", "--normalized", action="store_true", dest="normalized")
- args = vars(cmdparse.parse_args())
- if args['source'] == "hko":
- preGrabber = re.compile("</?pre>");
- with urllib.request.urlopen(HKOAddress[0]) as request:
- response = request.read().decode('big5hkscs')
- cutUp = preGrabber.split(response)[1].strip()
- stateValue = re.compile(r"No\. (\d\d?) - ([ \w]+)").search(cutUp)
- weatherData['summary'] = "{0} ({1})".format(stateValue.group(2).strip().title(), stateValue.group(1))
- weatherData['temperature'] = float(re.compile("(\d\d?) degrees Celsius").search(cutUp).group(1))
- weatherData['humidity'] = round(float(re.compile("(\d\d?) per cent").search(cutUp).group(1)) / 100, 2)
- with urllib.request.urlopen(HKOAddress[1]) as request:
- response = request.read().decode('ISO-8859-1')
- cutUp = preGrabber.split(response)[1].strip().splitlines()
- # 66 = Wong Chuk Hang WIND; 71 = HKO Observatory PRESSURE;; 35 ~ 38 are character rangea.
- weatherData['windSpeed'] = round(float(''.join(cutUp[66][35:38]).strip()) / 3.6, 3)
- weatherData['pressure'] = round(float(''.join(cutUp[71][23:]).strip()), 5)
- elif args['source'] == "fio":
- with urllib.request.urlopen(forecastIOAddress) as request:
- response = request.read().decode('utf-8')
- data = json.loads(response)
- weatherData = data['currently']
- tempUnit = "°C"
- presUnit = "hPa"
- if args['normalized']:
- weatherData['temperature'] += 273.15
- weatherData['pressure'] *= 100
- tempUnit = "K"
- presUnit = "Pa"
- message = args['source'] + " reports: State: {0[summary]}; T = {0[temperature]} {1}; v = {0[windSpeed]} m/s; Hum = {0[humidity]}; P = {0[pressure]} {2}".format(weatherData, tempUnit, presUnit)
- print(message)
- with open(homeFile, 'w') as writeTarget:
- writeTarget.write(message)
Advertisement
Add Comment
Please, Sign In to add comment