[Coursera 2코스]Using Python to Interact with the Operating System qwiklabs answer
#!/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_d..
2020.02.13
no image
[module] psutil 사용하기 (python system and process utilitis)
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의 경우 의미없는 값을 리턴합..
2020.02.09
no image
[module] shutil 모듈 사용하기 (High-level file operations)
shutil 모듈은 파일 또는 디렉토리에 대한 복사, 이동, 삭제 등에 관한 기능을 제공합니다. 복사하기 shutil.copy(src, dst) 파일 src 를 파일 또는 디렉토리 dst 에 복사 합니다. src 와 dst 는 문자열이어야합니다. copy()는 파일 데이터와 파일의 권한 모드를 복사합니다. 파일의 생성 및 수정 시간과 같은 다른 메타 데이터까지 복사할려면 copy2()를 대신 사용하면 됩니다. (버전 3.8 이후) 파일을 더 효율적으로 복사하기 위해서 플랫폼 별 fast-copy syscall을 사용할 수 있습니다. 파일 복사와 관련된 모든 기능 ( copyfile(), copy(), copy2(), copytree(), move()) 에서 fast-copy를 사용할 수 있습니다. fas..
2020.02.09
no image
[읽을 거리]Classes and Methods Cheat Sheet
Classes and Methods Cheat Sheet 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 objec..
2020.01.31
[읽을 거리]Dictionary Methods Cheat Sheet
Dictionary Methods Cheat Sheet Definition x = {key1:value1, key2:value2} Operations 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 ..
2020.01.30
[읽을 거리]Lists and Tuples Operations Cheat Sheet
Lists and Tuples Operations Cheat Sheet 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 seque..
2020.01.30
[읽을 거리] Formatting Strings Cheat Sheet
Formatting Strings Cheat Sheet 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 "bas..
2020.01.29
[읽을 거리]String Reference Cheat Sheet
String Reference Cheat Sheet 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] Access..
2020.01.29
#!/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의 사용률을 백분율로 리턴해줍니다.

 

psutil.cpu_times_percent(interval=None , percpu=False) 

cpu시간에 대한 사용율을 리턴합니다.

 

psutil.cpu_count(logical=True)

logical 플래그가 False라면 물리적 코어의 수를 리턴하고 True면 논리적 코어의 수를 리턴한다. 

 - Memory

psutil.virtual_memory()

시스템 메모리 사용량을 바이트 단위로 다음 항목을 포함하여 튜플로 리턴합니다.

total : 총 메모리

available : 시스템을 스왑하지 않고 프로세스에 즉시 제공할 수 있는 메모리. 실제 메모리 사용량을 모니터링 하는데 사용됩니다.

used : 사용되는 메모리, 플랫폼에 따라 다르게 계산됩니다. total - used 메모리가 반드시 free 메모리와 일치하지는 않습니다.

free : 실제 메모리 여유량.

active : 현재 사용중이거나 최근에 사용된 메모리

inactive : 사용중이 아닌 메모리

buffers : 파일 시스템, 메타 데이터와 같은 것들을 위한 캐시

shared : 여러 프로세스에서 동시에 액세스 가능한 메모리

slab : 커널 내부 데이터 구조 캐시

wired : 항상 ram에 남아있는 것으로 표시되는 메모리

 

psutil.swap_memory()

시스템 스왑 메모리 사용량을 다음 항목을 포함하여 튜플로 리턴합니다.

total : 총 스왑 메모리

used : 사용중인 스왑 메모리

free : 사용가능한 스왑 메모리

percent : 사용량

sin : 시스템이 디스크에서 스왑한 바이트 수 (누적)

sout : 시스템이 디스크에서 스왑한 바이트 수 (누적)

 - Disks

psutil.disk_partitions(all=False)

마운트된 모든 디스크 파티션을 "df" 명령어와 유사하게 장치, 마운트지점 및 파일 시스템 유형을 포함한 튜플로 리턴합니다.

 

psutil.disk_usage(path)

total, used, free, percent 항목을 포함하여 튜플로 반환합니다.

사용 예

https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py

 

 

 - Network

psutil.net_connections(kind='inet') 

시스템 전체 소켓 연결을 튜블로 리턴합니다. 

fd : socket file descriptor, 윈도우와 sunOS에서는 항상 -1

family : address family

type : address type

laddr : local address

raddr : remote address

status : TCP 연결의 상태

pid : 소켓이 연결된 process id

 

psutil.net_if_addrs()

key가 NIC 이름이고 값이 NIC에 할당된 주소인 튜플 목록인 딕셔너리로 리턴합니다.

family : address family

address : 기본 NIC 주소

netmask : netmask 주소

broadcast : broadcast 주소

ptp : 포인트 투 포인트 주소(일반적으로 VPN)

 

psutil.net_if_stats()

key가 NIC 이름이고 값이 NIC에 할당된 주소인 튜플 목록인 딕셔너리로 리턴합니다.

isup : NIC가 작동중인지 여부를 나타냄

duplex : duplex 통신 유형

speed : MB로 표시되는 NIC 속도

mtu : 바이트 단위로 표시되는 NIC의 최대 전송 단위

 

2. Process

psutil.pids()

현재 실행중인 PID를 정렬해 리턴합니다.

 

psutil.process_iter(attrs=None, ad_value=None, new_only=False) 

사용법 예:

>>> import psutil
>>> for proc in psutil.process_iter(attrs=['pid', 'name', 'username']):
...     print(proc.info)
...
{'name': 'systemd', 'pid': 1, 'username': 'root'}
{'name': 'kthreadd', 'pid': 2, 'username': 'root'}
{'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'}
...

딕셔너리로 데이터 구조 생성 예:

>>> import psutil
>>> procs = {p.pid: p.info for p in psutil.process_iter(attrs=['name', 'username'])}
>>> procs
{1: {'name': 'systemd', 'username': 'root'},
 2: {'name': 'kthreadd', 'username': 'root'},
 3: {'name': 'ksoftirqd/0', 'username': 'root'},
 ...}

이름으로 필터링 :

>>> 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)
...

 

psutil.pid_exists(pid) 

pid가 현재 프로세스 목록에 있는지 확인합니다. 

 

psutil.wait_procs(procs, timeout=None, callback=None) 

 

 

 

출처

https://psutil.readthedocs.io/en/latest/

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() 내부적으로 덜 효율적인 기능을 사용하여 자동으로 풀백됩니다.

 

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy,
                ignore_dangling_symlinks=False, dir_exist_ok=False)

copytree는 src를 루트로 하는 전체 디렉토리 트리를 dst에 복사합니다.

dir_exist_ok는 dst의 누락된 상위폴더가 이미 존재하는 경우 예외를 발생시킬지 여부를 체크합니다.

symlink가 True면 src 디렉토리에 있는 심볼릭링크 들은 dst 디렉토리에 심볼릭 링크로 생성됩니다.

symlink가 False면 src 디렉토리에 심볼릭링크에 연결된 파일이 dst 디렉토리로 복사됩니다.

symlink가 False이고 심볼릭링크에 연결된 파일이 없을때 error가 발생하는데 이 때 ignore_dangling_symlinks 플래그를 True로 설정하면 error메세지가 발생하지 않습니다.

 

shutil.rmtree(path, ignore_errors = False, onerror = None)

path 디렉토리를 삭제합니다. ignore_errors가 True라면 삭제 실패시 발생하는 에러는 무시됩니다. ingore_errors가 False거나 생략되면 onerror에 지정된 핸들러를 호출하여 처리하거나 예외를 발생시킵니다.

 

shutil.move(src, dst, copy_function = copy2)

src의 파일 또는 디렉토리를 dst로 이동하고 리턴합니다.

dst의 대상이 이미 존재하는 디렉토리라면 src가 해당 디렉토리 안으로 이동합니다. 또는 대상이 이미 존재하지만 디렉토리가 아니라면 덮어 쓸수도 있습니다.

 

shutil.disk_usage(path)

path에 대한 디스크 사용량 통계를 total, used 및 free 속성을 가진 튜플을 바이트 단위로 리턴합니다. 

 

shutil.which(cmd)

cmd가 호출된 경우 cmd의 경로 디렉토리를 반환합니다.

 

출처

https://docs.python.org/3/library/shutil.html

Classes and Methods Cheat Sheet

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:

 

출처 : google crash course on python 강의

Dictionary Methods Cheat Sheet

Definition

x = {key1:value1, key2:value2}

Operations

  • 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

Check out the official documentation for dictionary operations and methods.

 

https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

 

Built-in Types — Python 3.8.1 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

 

출처 : google crash course on python 강의

Lists and Tuples Operations Cheat Sheet

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

Check out the official documentation for sequence operations.

List-specific operations and methods

  • list[i] = x Replaces the element at index i with x
  • list.append(x) Inserts x at the end of the list
  • list.insert(i, x) Inserts x at index i
  • list.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.
  • list.remove(x) Removes the first occurrence of x in the list
  • list.sort() Sorts the items in the list
  • list.reverse() Reverses the order of items of the list
  • list.clear() Removes all the items of the list
  • list.copy() Creates a copy of the list
  • list.extend(other_list) Appends all the elements of other_list at the end of list

Most of these methods come from the fact that lists are mutable sequences. For more info, see the official documentation for mutable sequences and the list specific documentation.

List comprehension

  • [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.

출처 : google crash course on python 강의

Formatting Strings Cheat Sheet

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.

Official documentation for the format string syntax

Formatting expressions

ExprMeaningExample

{:d} integer value '{:d}'.format(10.5) → '10'
{:.2f} floating point with that many decimals '{:.2f}'.format(0.5) → '0.50'
{:.2s} string with that many characters '{:.2s}'.format('Python') → 'Py'
{:<6s} string aligned to the left that many spaces '{:<6s}'.format('Py') → 'Py    '
{:>6s} string aligned to the right that many spaces '{:<6s}'.format('Py') → '    Py'
{:^6s} string centered in that many spaces '{:<6s}'.format('Py') → '  Py '

Check out the official documentation for all available expressions.

Old string formatting (Optional)

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 is no longer recommended for 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).

"Item: %s - Amount: %d - Price: %.2f" % (item, amount, price)

The formatting expressions are mostly the same as those of the format() method. 

Check out the official documentation for old string formatting.

Formatted string literals (Optional)

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.

Examples:

>>> name = "Micah"

>>> print(f'Hello {name}')

Hello Micah

>>> item = "Purple Cup"

>>> amount = 5

>>> price = amount * 3.25

>>> print(f'Item: {item} - Amount: {amount} - Price: {price:.2f}')

Item: Purple Cup - Amount: 5 - Price: 16.25

Check out the official documentation for f-strings.

 

출처 : google crash course on python 강의

String Reference Cheat Sheet

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

https://docs.python.org/3/library/stdtypes.html#string-methods

 

Built-in Types — Python 3.8.1 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org