[Coursera 2코스]Using Python to Interact with the Operating System qwiklabs answer
|2020. 2. 13. 10:28
#!/usr/bin/env python3
import subprocess
import csv
import re
import operator
def report_error():
error_dic = {}
error_list = subprocess.check_output(["grep","ERROR","syslog.log"]).decode()
error_list = error_list.split('\n')
for i in range(len(error_list)-1):
line = error_list[i]
value = re.search(r"ticky: ERROR ([\w ]*) ", line).group(1)
if value in error_dic:
error_dic[value]+=1
else:
error_dic[value]=1
error_dic = sorted(error_dic.items(), key = operator.itemgetter(1), reverse=True)
error_dic.insert(0,('Error', 'Count'))
with open("error_message.csv", 'w', newline='') as file:
writer = csv.writer(file)
for row in error_dic:
writer.writerow(row)
def report_user():
user_dic = {}
user_list = subprocess.check_output(["cat","syslog.log"]).decode()
user_list = user_list.split('\n')
for i in range(len(user_list)-1):
line = user_list[i]
user = re.search(r"[(](.*)[)]$", line).group(1)
type = re.search(r"ticky: (\w*)", line).group(1)
if user in user_dic:
if type == 'ERROR':
user_dic[user][1] += 1
else:
user_dic[user][0] += 1
else:
if type == 'ERROR':
user_dic[user] = [0,1]
else:
user_dic[user] = [1,0]
user_dic = sorted(user_dic.items(), key=operator.itemgetter(0))
user_dic.insert(0,('Username', 'INFO', 'ERROR'))
with open("user_statistics.csv", 'w', newline='') as file:
writer = csv.writer(file)
for row in user_dic:
row = [row[0], row[1][0], row[1][1]]
writer.writerow(row)
report_error()
report_user()
'프로그래밍 언어 > [Python]스터디' 카테고리의 다른 글
[module] psutil 사용하기 (python system and process utilitis) (0) | 2020.02.09 |
---|---|
[module] shutil 모듈 사용하기 (High-level file operations) (0) | 2020.02.09 |
[읽을 거리]Classes and Methods Cheat Sheet (0) | 2020.01.31 |
[읽을 거리]Dictionary Methods Cheat Sheet (0) | 2020.01.30 |
[읽을 거리]Lists and Tuples Operations Cheat Sheet (0) | 2020.01.30 |