본문 바로가기

파이썬/파이썬 예제

python으로 cpu 사용량과 memory 체크하기

# 파이썬을 활용하여 AWS EC2의 CPU 사용량과 Memory 체크하기

1. 작업 폴더를 생성합니다.

mkdir python3-test
cd python3-test

2. 파이썬 파일을 생성 합니다.

vi python3-test-monitoring.py

3. 파이썬 코드를 작성하고 저장합니다.

import os
import psutil

def _check_usage_of_cpu_and_memory():
    
    pid = os.getpid()
    py  = psutil.Process(pid)
    
    cpu_usage   = os.popen("ps aux | grep " + str(pid) + " | grep -v grep | awk '{print $3}'").read()
    cpu_usage   = cpu_usage.replace("\n","")
    
    memory_usage  = round(py.memory_info()[0] /2.**30, 2)
    
    print("cpu usage\t\t:", cpu_usage, "%")
    print("memory usage\t\t:", memory_usage, "%")

4. 작성한 파일을 실행 합니다.

python3 python3-test-monitoring.py

- 만약 아래와 같은 오류가 발생 한다면,

ubuntu@ip-172-16-0-13:~/python3-test$ python3 python3-test-monitoring.py
Traceback (most recent call last):
  File "python3-test-monitoring.py", line 2, in <module>
    import psutil
ModuleNotFoundError: No module named 'psutil'

- 해당 라이브러리를 설치해주자

sudo pip install --upgrade psutil
ubuntu@ip-172-16-0-13:~/python3-test$ sudo pip install --upgrade psutil
Collecting psutil
  Downloading psutil-5.8.0-cp38-cp38-manylinux2010_x86_64.whl (296 kB)
     |████████████████████████████████| 296 kB 1.7 MB/s
Installing collected packages: psutil
Successfully installed psutil-5.8.0

- 다시 실행해보자

python3 python3-test-monitoring.py

- 아무 반응이 읎다...

- 아무래도 ps aux | grep " + str(pid) + " | grep -v grep | awk '{print $3} 요 부분이 잘못된거 같다. 수정을 해보자~