-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgetweather2.py
More file actions
53 lines (43 loc) · 1.57 KB
/
getweather2.py
File metadata and controls
53 lines (43 loc) · 1.57 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
from threading import Thread
import json
from urllib.request import urlopen
import time
cities = ['Boulder', 'Atlanta', 'San Francisco',
'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={}&units=imperial'
'&&APPID=10d4440bbaa8581bb8da9bd1fbea5617')
response = urlopen(url_template.format(self.city))
data = json.loads(response.read().decode())
self.temperature = data['main']['temp']
shared_dict[self.city] = round(self.temperature)
shared_dict = {}
threads = [TempGetter(c) for c in cities]
start = time.time()
# start all 10 threads
for thread in threads:
thread.start()
# wait for all 10 threads to complete
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))
print(shared_dict)