-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-stats.py
executable file
·60 lines (47 loc) · 1.52 KB
/
101-stats.py
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
#!/usr/bin/python3
"""Reads from standard input and computes metrics.
After every ten lines or the input of a keyboard
interruption (CTRL + C),
prints the following statistics:
- Total file size up to that point.
- Count of read status codes up to that point.
"""
def print_stats(size, status_codes):
"""Print accumulated metrics.
Args:
size (int): The accumulated read file size.
status_codes (dict): The accumulated count of status codes.
"""
print("File size: {}".format(size))
for key in sorted(status_codes):
print("{}: {}".format(key, status_codes[key]))
if __name__ == "__main__":
import sys
size = 0
status_codes = {}
valid_codes = ['200', '301', '400', '401', '403', '404', '405', '500']
count = 0
try:
for line in sys.stdin:
if count == 10:
print_stats(size, status_codes)
count = 1
else:
count += 1
line = line.split()
try:
size += int(line[-1])
except (IndexError, ValueError):
pass
try:
if line[-2] in valid_codes:
if status_codes.get(line[-2], -1) == -1:
status_codes[line[-2]] = 1
else:
status_codes[line[-2]] += 1
except IndexError:
pass
print_stats(size, status_codes)
except KeyboardInterrupt:
print_stats(size, status_codes)
raise