-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsimpleWeather.py
More file actions
240 lines (191 loc) · 7.7 KB
/
simpleWeather.py
File metadata and controls
240 lines (191 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simple command-line weather app using Python 3 and following modules:
http://docs.python.org/3.3/library/optparse.html
http://docs.python.org/3.3/library/json.html
http://www.python-requests.org/en/latest/
https://pypi.python.org/pypi/PrettyTable
Major thanks to the creators of the following APIs:
https://developers.google.com/maps/documentation/geocoding/
https://developer.forecast.io/
http://freegeoip.net/
http://ip.42.pl
And also to the people over at gnuplot:
http://www.gnuplot.info/
"""
import datetime as dt
import os
import json
import requests
import subprocess
import sys
import time
from optparse import OptionParser
from prettytable import PrettyTable
NUM_HOURLY_RECORDS = 16
speed = ["mph", "m/s"]
degrees = ["°F", "°C"]
length = ["in", "cm"]
parser = OptionParser()
with open(os.path.join(os.path.dirname(__file__), "private.json")) as f:
private = json.loads(f.read())
api_key = private["api_key"]
loc = private["latitude"] + "," + private["longitude"]
try:
ip = requests.get("http://ip.42.pl/raw").text
geo_url = "http://freegeoip.net/{0}/{1}".format("json", ip)
location_info = requests.get(geo_url).json()
longitude = str(location_info["longitude"])
latitude = str(location_info["latitude"])
loc = latitude + "," + longitude
except Exception as e:
print("Failed to detect location. Using default value from private.json")
parser.set_defaults(debug=False, graphics=False, location="", metric=False, now=False, today=False, week=False)
parser.add_option("-d", "--debug", action="store_true", help="show debug messages")
parser.add_option("-g", "--graphics", action="store_true", help="display visuals for weekly forecasts")
parser.add_option("-l", "--location", help="specify a location other than the default")
parser.add_option("-m", "--metric", action="store_true", help="use metric rather than imperial units")
parser.add_option("-n", "--now", action="store_true", help="display the current weather summary")
parser.add_option("-t", "--today", action="store_true", help="display today's hourly forecast")
parser.add_option("-w", "--week", action="store_true", help="display the weekly forecast")
(options, args) = parser.parse_args()
if options.debug:
print()
print("Options: " + str(options))
print("Args: " + str(args))
if options.location:
loc_url = "http://maps.googleapis.com/maps/api/geocode/json?address=M{0}&sensor=false".format(options.location)
loc_info = requests.get(loc_url).json()
lat_long = loc_info["results"][0]["geometry"]["location"]
latitude = lat_long["lat"]
longitude = lat_long["lng"]
loc = str(latitude) + "," + str(longitude)
url = "https://api.forecast.io/forecast/{0}/{1}".format(api_key, loc)
if options.metric:
url += "?units=si"
try:
response = requests.get(url).json()
except:
print("There was an error retrieving the forecast.")
print("Please check your internet connection and try again.")
sys.exit()
def plot_weekly():
highs = []
lows = []
rain = []
days = []
for day in response["daily"]["data"]:
highs.append(str(day["temperatureMax"]))
lows.append(str(day["temperatureMin"]))
rain.append(str(day["precipProbability"]))
try: # this may be too hacky, buuuut it works for now...
days.append(str(int(days[len(days) - 1]) + 1))
except IndexError:
days.append(str(dt.datetime.weekday(dt.datetime.fromtimestamp(day["time"])) + 1))
start_day = time.ctime(response["daily"]["data"][0]["time"]).split(" ")
start_day = list(filter(None, start_day)) # required since time.ctime() pads left with an extra space for 1-digit dates
start_day_pretty = start_day[0] + ' ' + start_day[1] + ' ' + start_day[2]
end_day = time.ctime(response["daily"]["data"][-1]["time"]).split(" ")
end_day = list(filter(None, end_day)) # required since time.ctime() pads left with an extra space for 1-digit dates
end_day_pretty = end_day[0] + ' ' + end_day[1] + ' ' + end_day[2]
period = start_day_pretty + " - " + end_day_pretty
plot_data = []
for day, low, high in zip(days, lows, highs):
plot_data.append(day + "\t" + low + "\t" + high + "\n")
gnuplot = subprocess.Popen(['gnuplot', '-persist'], stdin=subprocess.PIPE).stdin
# Find the next value mod 5 == 0 next to the plot data's minimum and maximum
plot_min = int(round(min(float(x) for x in lows) / 5.0) * 5.0) - 5
plot_max = int(round(max(float(x) for x in highs) / 5.0) * 5.0) + 5
# adjust the plot height so that y-axis spacing is consistent
plot_height = int((plot_max - plot_min) / 2.5) + 6
gnuplot = subprocess.Popen(['gnuplot', '-persist'], stdin=subprocess.PIPE).stdin
plot_title = "'High and Low Temperatures, {0}'\n".format(period)
setup_gnuplot(gnuplot, plot_title, plot_height, days[0], days[-1], plot_min, plot_max)
gnuplot.write("plot '-' u 1:2 w l, '-' u 1:3 w l\n".encode())
for line in plot_data: # iterate through once for the lows
gnuplot.write(line.encode())
gnuplot.write("e\n".encode()) # 'e' is the end-of-input marker for gnuplot
for line in plot_data: # then again for the highs (per gnuplot docs)
gnuplot.write(line.encode())
gnuplot.write("e\n".encode())
gnuplot.flush()
def setup_gnuplot(gnuplot_proc, title, height, xmin, xmax, ymin, ymax):
gnuplot_proc.write("set terminal dumb size 79, {0}\n".format(height).encode()) # allows space for title and temp increments of 5
gnuplot_proc.write("set title {0}\n".format(title).encode())
gnuplot_proc.write("set nokey\n".encode())
gnuplot_proc.write("set xdtics\n".encode())
gnuplot_proc.write("set xrange [{0}:{1}]\n".format(xmin, xmax).encode())
gnuplot_proc.write("set yrange [{0}:{1}]\n".format(ymin, ymax).encode())
gnuplot_proc.write("set ytics 0,5\n".encode())
gnuplot_proc.write("set tic scale 0\n".encode())
def display_current_weather():
summary = response["currently"]["summary"]
current_temp = response["currently"]["temperature"]
current_wind = response["currently"]["windSpeed"]
chance_of_rain = response["currently"]["precipProbability"]
print()
print("Current conditions: {0}".format(summary))
print("Current temperature: {0}".format(current_temp) + " " + degrees[options.metric])
print("Winds: {0} ".format(current_wind) + speed[options.metric])
print("Chance of precipitation: {0}%".format(chance_of_rain))
print()
def display_hourly_forecast():
day_summary = response["hourly"]["summary"]
print()
print("Hourly forecast: {0}".format(day_summary))
table = PrettyTable([
"Time",
"Summary",
"Precipitation",
"Temperature",
"Wind",
"Humidity"
])
for hour in response["hourly"]["data"][0:NUM_HOURLY_RECORDS]:
dt = time.ctime(hour["time"]).split()
short_dt = dt[0] + " " + dt[3][0:5]
table.add_row([
short_dt,
hour["summary"],
str(int(hour["precipProbability"]*100)) + "%",
str(hour["temperature"]) + " " + degrees[options.metric],
str(hour["windSpeed"]) + " " + speed[options.metric],
str(int(hour["humidity"]*100)) + "%"
])
print(table)
def display_weekly_forecast():
week_summary = response["daily"]["summary"]
print()
print("Forecast for the coming week: {0}".format(week_summary))
table = PrettyTable([
"Day",
"Summary",
"Precipitation",
"High",
"Low",
"Wind",
"Humidity"
])
for day in response["daily"]["data"]:
dt = time.ctime(day["time"]).split()
short_dt = dt[0] + " " + dt[1] + " " + dt[2]
table.add_row([
short_dt,
day["summary"],
str(int(day["precipProbability"]*100)) + "%",
str(day["temperatureMax"]) + " " + degrees[options.metric],
str(day["temperatureMin"]) + " " + degrees[options.metric],
str(day["windSpeed"]) + " " + speed[options.metric],
str(int(day["humidity"]*100)) + "%"
])
print(table)
if __name__ == "__main__":
if options.now:
display_current_weather()
if options.graphics:
plot_weekly()
if options.today:
display_hourly_forecast()
if options.week:
display_weekly_forecast()