Q. 파이썬으로 cpu,ram,네트워크의 사용량을 1초마다 출력하는 프로그램을 작성해줘
A.pip install psutil
import psutil import time def print_system_usage(): while True: # CPU 사용량 및 코어 수 가져오기 cpu_percent = psutil.cpu_percent(interval=1, percpu=True) num_cores = psutil.cpu_count() # RAM 사용량 가져오기 ram = psutil.virtual_memory() ram_percent = ram.percent # 네트워크 정보 가져오기 network = psutil.net_io_counters() sent_bytes = network.bytes_sent received_bytes = network.bytes_recv # 정보 출력 print(f"CPU 사용량 (%): {cpu_percent}") print(f"총 CPU 코어 수: {num_cores}") print(f"RAM 사용량 (%): {ram_percent}") print(f"전송된 데이터 (bytes): {sent_bytes}") print(f"수신된 데이터 (bytes): {received_bytes}") print("=" * 40) time.sleep(1) if __name__ == "__main__": print_system_usage()
결과물:
Q.파이썬으로 간단한 GUI를 이용해서 cpu,ram사용량을 1초마다 표시하는 프로그램을 작성해줘
A.import psutil import tkinter as tk from tkinter import Label import threading import time class SystemMonitorApp: def __init__(self, root): self.root = root self.root.title("System Monitor") self.cpu_label = Label(root, text="CPU 사용량:") self.cpu_label.pack() self.ram_label = Label(root, text="RAM 사용량:") self.ram_label.pack() self.update_labels() def update_labels(self): cpu_percent = psutil.cpu_percent(interval=1) ram = psutil.virtual_memory() ram_percent = ram.percent self.cpu_label.config(text=f"CPU 사용량: {cpu_percent:.2f}%") self.ram_label.config(text=f"RAM 사용량: {ram_percent:.2f}%") self.root.after(1000, self.update_labels) def main(): root = tk.Tk() app = SystemMonitorApp(root) root.mainloop() if __name__ == "__main__": main()
결과물: