-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetweather.py
More file actions
executable file
·50 lines (40 loc) · 1.4 KB
/
getweather.py
File metadata and controls
executable file
·50 lines (40 loc) · 1.4 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
from threading import Thread
import json
from urllib.request import urlopen
import time
cities = ['Boulder', 'Atlanta', 'Germantown',
'Reno', 'Honolulu', 'Zurich', 'Dubai',
'Dublin','Stuttgart', 'Rome']
class TempGetter(Thread):
def __init__(self, city):
"""Initialize our thread
In the previous example, our class which extended
Thread did not need an __init__ method, because
there was no per-thread information to store.
Which means that the __init__ method from the
superclass (Thread) was called automatically.
Here, because we need to store per-thread
information (the city), we have to explicitly
call the __init__ method of Thread.
"""
super().__init__()
self.city = city
def run(self):
url_template = (
'http://api.openweathermap.org/data/2.5/'
'weather?q={},CA&units=imperial'
'&&APPID=10d4440bbaa8581bb8da9bd1fbea5617')
response = urlopen(url_template.format(self.city))
data = json.loads(response.read().decode())
self.temperature = data['main']['temp']
threads = [TempGetter(c) for c in cities]
start = time.time()
for thread in threads:
thread.start()
for thread in threads:
thread.join()
for thread in threads:
print("it is {0.temperature:.0f}°F in {0.city}"
.format(thread))
print("Got {} temps in {} seconds"
.format(len(threads), time.time() - start))