#!/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()
psutil은 주로 시스템 모니터링, 프로파일링, 프로세스 리소스 제한 및 실행중인 프로세스 관리에 유용합니다.
psutil은 기본적으로 제공되는 모듈이 아닙니다. pip를 이용해 설치하여야 합니다.
1. 시스템 관련기능(System related fuctions) - CPU
psutil.cpu_times(percpu=False)
cpu 시간을 튜플로 리턴합니다. percpu가 True로 되면 시스템의 각 cpu에 대해서 튜플로 리턴합니다.
psutil.cpu_percent(interval=None, percpu=False)
현재 시스템의 전체 cpu 사용률을 백분율로 리턴해줍니다. interval 옵션의 경우 최소 0.1에서 몇초간 호출하는 것을 추천합니다. 0이나 none의 경우 의미없는 값을 리턴합니다. percpu가 True로 되면 시스템의 각 cpu의 사용률을 백분율로 리턴해줍니다.
>>> import psutil
>>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']]
[{'name': 'python3', 'pid': 21947},
{'name': 'python', 'pid': 23835}]
새로운 프로세스만 가져오기 :
>>> import psutil
>>> for proc in psutil.process_iter(attrs=['pid', 'name'], new_only=True):
... print(proc.info)
...
shutil 모듈은 파일 또는 디렉토리에 대한 복사, 이동, 삭제 등에 관한 기능을 제공합니다.
복사하기
shutil.copy(src, dst)
파일src를 파일 또는 디렉토리dst 에 복사합니다.src와dst는 문자열이어야합니다.
copy()는 파일 데이터와 파일의 권한 모드를 복사합니다. 파일의 생성 및 수정 시간과 같은 다른 메타 데이터까지 복사할려면 copy2()를 대신 사용하면 됩니다.
(버전 3.8 이후) 파일을 더 효율적으로 복사하기 위해서 플랫폼 별 fast-copy syscall을 사용할 수 있습니다.
파일 복사와 관련된 모든 기능 ( copyfile(), copy(), copy2(), copytree(), move()) 에서 fast-copy를 사용할 수 있습니다. fast-copy는 작업이 커널 내에서 발생하여 "outfd.write(infd.read())"와 달리 Python userspace buffers 사용을 피할 수 있습니다.
macOS에서는 fcopyfile linux는 os.sendfile()이 사용됩니다.
fast-copy가 실패하고 데이터가 기록되지 않은 경우 shutil은 copyfileobj() 내부적으로 덜 효율적인 기능을 사용하여 자동으로 풀백됩니다.
In the past few videos, we’ve seen how to define classes and methods in Python. Here, you’ll find a run-down of everything we’ve covered, so you can refer to it whenever you need a refresher.
Defining classes and methods
Classes and Instances
Classes define the behavior of all instances of a specific class.
Each variable of a specific class is an instance or object.
Objects can have attributes, which store information about the object.
You can make objects do work by calling their methods.
The first parameter of the methods (self) represents the current instance.
Methods are just like functions, but they can only be used through a class.
Special methods
Special methods start and end with __.
Special methods have specific names, like __init__ for the constructor or __str__ for the conversion to string.
Documenting classes, methods and functions
You can add documentation to classes, methods, and functions by using docstrings right after the definition. Like this:
len(dictionary) - Returns the number of items in the dictionary
for key in dictionary - Iterates over each key in the dictionary
for key, value in dictionary.items() - Iterates over each key,value pair in the dictionary
if key in dictionary - Checks whether the key is in the dictionary
dictionary[key] - Accesses the item with key key of the dictionary
dictionary[key] = value - Sets the value associated with key
del dictionary[key] - Removes the item with key key from the dictionary
Methods
dict.get(key, default) - Returns the element corresponding to key, or default if it's not present
dict.keys() - Returns a sequence containing the keys in the dictionary
dict.values() - Returns a sequence containing the values in the dictionary
dict.update(other_dictionary) - Updates the dictionary with the items coming from the other dictionary. Existing entries will be replaced; new entries will be added.
dict.clear() - Removes all the items of the dictionary
Lists and tuples are both sequences, so they share a number of sequence operations. But, because lists are mutable, there are also a number of methods specific just to lists. This cheat sheet gives you a run down of the common operations first, and the list-specific operations second.
Common sequence operations
len(sequence) Returns the length of the sequence
for element in sequence Iterates over each element in the sequence
if element in sequence Checks whether the element is part of the sequence
sequence[i] Accesses the element at index i of the sequence, starting at zero
sequence[i:j] Accesses a slice starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(sequence) by default.
for index, element in enumerate(sequence) Iterates over both the indexes and the elements in the sequence at the same time
[expression for variable in sequence] Creates a new list based on the given sequence. Each element is the result of the given expression.
[expression for variable in sequence if condition] Creates a new list based on the given sequence. Each element is the result of the given expression; elements only get added if the condition is true.
Python offers different ways to format strings. In the video, we explained the format() method. In this reading, we'll highlight three different ways of formatting strings. For this course you only need to know the format() method. But on the internet, you might find any of the three, so it's a good idea to know that the others exist.
Using the format() method
"base string with {} placeholders".format(variables)
The format method returns a copy of the string where the {} placeholders have been replaced with the values of the variables. These variables are converted to strings if they weren't strings already. Empty placeholders are replaced by the variables passed to format in the same order.
"{0} {1}".format(first, second)
If the placeholders indicate a number, they’re replaced by the variable corresponding to that order (starting at zero).
"{var1} {var2}".format(var1=value1, var2=value2)
If the placeholders indicate a field name, they’re replaced by the variable corresponding to that field name. This means that parameters to format need to be passed indicating the field name.
"{:exp1} {:exp2}".format(value1, value2)
If the placeholders include a colon, what comes after the colon is a formatting expression. See below for the expression reference.
The format() method was introduced in Python 2.6. Before that, the % (modulo) operator could be used to get a similar result. While this method isno longer recommendedfor new code, you might come across it in someone else's code. This is what it looks like:
"base string with %s placeholder" % variable
The % (modulo) operator returns a copy of the string where the placeholders indicated by % followed by a formatting expression are replaced by the variables after the operator.
"base string with %d and %d placeholders" % (value1, value2)
To replace more than one value, the values need to be written between parentheses. The formatting expression needs to match the value type.
"%(var1) %(var2)" % {var1:value1, var2:value2}
Variables can be replaced by name using a dictionary syntax (we’ll learn about dictionaries in an upcoming video).
This feature was added in Python 3.6 and isn’t used a lot yet. Again, it's included here in case you run into it in the future, but it's not needed for this or any upcoming courses.
A formatted string literal or f-string is a string that starts with 'f' or 'F' before the quotes. These strings might contain {} placeholders using expressions like the ones used for format method strings.
The important difference with the format method is that it takes the value of the variables from the current context, instead of taking the values from parameters.
In Python, there are a lot of things you can do with strings. In this cheat sheet, you’ll find the most common string operations and string methods.
String operations
len(string) Returns the length of the string
for character in string Iterates over each character in the string
if substring in string Checks whether the substring is part of the string
string[i] Accesses the character at index i of the string, starting at zero
string[i:j] Accesses the substring starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(string) by default.
String methods
string.lower() / string.upper() Returns a copy of the string with all lower / upper case characters
string.lstrip() / string.rstrip() / string.strip() Returns a copy of the string without left / right / left or right whitespace
string.count(substring) Returns the number of times substring is present in the string
string.isnumeric() Returns True if there are only numeric characters in the string. If not, returns False.
string.isalpha() Returns True if there are only alphabetic characters in the string. If not, returns False.
string.split() / string.split(delimiter) Returns a list of substrings that were separated by whitespace / delimiter
string.replace(old, new) Returns a new string where all occurrences of old have been replaced by new.
delimiter.join(list of strings) Returns a new string with all the strings joined by the delimiter