Python Tool: CPU RAM DISK

Mit diesem Python-Skript kannst du die RAM-Größe und Auslastung, die CPU-Auslastung (gesamt und pro Kern) und die Details zu allen erkannten Festplatten/Partitionen visualisieren.




#!/usr/bin/env python3
# *****************************************************************************
# Grafische Oberfläche (PyQt6) zur Visualisierung von: RAM-Größe und Auslastung
# CPU-Auslastung (gesamt und pro Kern). Details zu allen erkannten 
# Festplatten/Partitionen. Das Fenster erscheint zentriert auf dem Bildschirm 
# und hat eine feste Größe (nicht vergrößerbar, kein Maximieren möglich).
# Installation der Abhängigkeit: pip install PyQt6 psutil
# Start: python system_monitor_gui.py         (c) Hans Busche Datum: 10.07.2026
# *****************************************************************************
import sys
import psutil

from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QScreen
from PyQt6.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QGroupBox,
    QProgressBar,
    QGridLayout,
)

# *****************************************************************************
# Wandelt eine Byte-Anzahl in eine lesbare Größe um (z. B. 8.2 GB).
# *****************************************************************************
def bytes_lesbar(anzahl_bytes: int) -> str:
    schritt = 1024.0
    for einheit in ["B", "KB", "MB", "GB", "TB", "PB"]:
        if anzahl_bytes < schritt:
            return f"{anzahl_bytes:.1f} {einheit}"
        anzahl_bytes /= schritt
    return f"{anzahl_bytes:.1f} EB"

# *****************************************************************************
# Fenster, RAM-Bereich, CPU-Bereich, Festplatten-Bereich und Timer für 
# Live-Aktualisierung
# *****************************************************************************
class HauptFenster(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("System-Monitor: RAM, CPU & Festplatten")
        # Fenstergröße festlegen und Vergrößern/Maximieren unterbinden
        self.breite = 620
        self.hoehe = 640
        self.setFixedSize(self.breite, self.hoehe)
        zentral = QWidget()
        self.setCentralWidget(zentral)
        haupt_layout = QVBoxLayout(zentral)

        # ---------------- RAM-Bereich ----------------
        ram_box = QGroupBox("Arbeitsspeicher (RAM)")
        ram_layout = QVBoxLayout()
        self.ram_balken = QProgressBar()
        self.ram_balken.setMinimum(0)
        self.ram_balken.setMaximum(100)
        self.ram_balken.setStyleSheet(self._balken_stil("#2e7d32"))
        ram_layout.addWidget(self.ram_balken)
        self.ram_text = QLabel("–")
        self.ram_text.setStyleSheet("font-size: 13px;")
        ram_layout.addWidget(self.ram_text)
        ram_box.setLayout(ram_layout)
        haupt_layout.addWidget(ram_box)

        # ---------------- CPU-Bereich ----------------
        cpu_box = QGroupBox("Prozessor (CPU)")
        cpu_layout = QVBoxLayout()
        self.cpu_gesamt_balken = QProgressBar()
        self.cpu_gesamt_balken.setMinimum(0)
        self.cpu_gesamt_balken.setMaximum(100)
        self.cpu_gesamt_balken.setStyleSheet(self._balken_stil("#1565c0"))
        cpu_layout.addWidget(self.cpu_gesamt_balken)
        self.cpu_text = QLabel("–")
        self.cpu_text.setStyleSheet("font-size: 13px;")
        cpu_layout.addWidget(self.cpu_text)
        # Kerne einzeln anzeigen
        self.kern_layout = QGridLayout()
        self.kern_balken = []
        anzahl_kerne = psutil.cpu_count(logical=True) or 1
        for i in range(anzahl_kerne):
            label = QLabel(f"Kern {i + 1}")
            balken = QProgressBar()
            balken.setMinimum(0)
            balken.setMaximum(100)
            balken.setTextVisible(True)
            balken.setStyleSheet(self._balken_stil("#1976d2"))
            zeile = i // 2
            spalte = (i % 2) * 2
            self.kern_layout.addWidget(label, zeile, spalte)
            self.kern_layout.addWidget(balken, zeile, spalte + 1)
            self.kern_balken.append(balken)
        cpu_layout.addLayout(self.kern_layout)
        cpu_box.setLayout(cpu_layout)
        haupt_layout.addWidget(cpu_box)

        # ---------------- Festplatten-Bereich ----------------
        disk_box = QGroupBox("Festplatten / Partitionen")
        self.disk_layout = QVBoxLayout()
        disk_box.setLayout(self.disk_layout)
        haupt_layout.addWidget(disk_box)
        haupt_layout.addStretch()

        # ---------------- Timer für Live-Aktualisierung ----------------
        self.timer = QTimer()
        self.timer.timeout.connect(self.aktualisieren)
        self.timer.start(1500)  # alle 1,5 Sekunden
        # Festplatten einmalig aufbauen (Struktur ändert sich selten)
        self.disk_balken = {}
        self._festplatten_aufbauen()
        # Erste Anzeige sofort
        self.aktualisieren()

    def _balken_stil(self, farbe: str) -> str:
        return f"""
            QProgressBar {{
                border: 1px solid #bbbbbb;
                border-radius: 4px;
                text-align: center;
                height: 18px;
            }}
            QProgressBar::chunk {{
                background-color: {farbe};
                border-radius: 3px;
            }}
        """

    def _festplatten_aufbauen(self):
        """Erstellt für jede gefundene Partition eine Zeile mit Balken."""
        partitionen = psutil.disk_partitions(all=False)
        for p in partitionen:
            try:
                nutzung = psutil.disk_usage(p.mountpoint)
            except (PermissionError, FileNotFoundError, OSError):
                continue
            zeile_widget = QWidget()
            zeile_layout = QHBoxLayout(zeile_widget)
            zeile_layout.setContentsMargins(0, 0, 0, 0)
            beschriftung = QLabel(f"{p.device}  ({p.mountpoint})")
            beschriftung.setMinimumWidth(180)
            zeile_layout.addWidget(beschriftung)
            balken = QProgressBar()
            balken.setMinimum(0)
            balken.setMaximum(100)
            balken.setStyleSheet(self._balken_stil("#ef6c00"))
            zeile_layout.addWidget(balken)
            self.disk_layout.addWidget(zeile_widget)
            self.disk_balken[p.mountpoint] = balken

    def aktualisieren(self):
        # ---- RAM ----
        ram = psutil.virtual_memory()
        self.ram_balken.setValue(int(ram.percent))
        self.ram_text.setText(
            f"Belegt: {bytes_lesbar(ram.used)} von {bytes_lesbar(ram.total)}  "
            f"({ram.percent:.1f} %)   |   Frei: {bytes_lesbar(ram.available)}"
        )

        # ---- CPU ----
        cpu_gesamt = psutil.cpu_percent(interval=None)
        self.cpu_gesamt_balken.setValue(int(cpu_gesamt))
        anzahl_kerne_logisch = psutil.cpu_count(logical=True)
        anzahl_kerne_physisch = psutil.cpu_count(logical=False)
        self.cpu_text.setText(
            f"Gesamtauslastung: {cpu_gesamt:.1f} %   |   "
            f"Kerne: {anzahl_kerne_physisch} physisch / {anzahl_kerne_logisch} logisch"
        )

        kern_werte = psutil.cpu_percent(interval=None, percpu=True)
        for balken, wert in zip(self.kern_balken, kern_werte):
            balken.setValue(int(wert))

        # ---- Festplatten ----
        for mountpoint, balken in self.disk_balken.items():
            try:
                nutzung = psutil.disk_usage(mountpoint)
                balken.setValue(int(nutzung.percent))
                balken.setFormat(
                    f"{nutzung.percent:.1f} %  "
                    f"({bytes_lesbar(nutzung.used)} von {bytes_lesbar(nutzung.total)})"
                )
            except (PermissionError, FileNotFoundError, OSError):
                balken.setFormat("nicht verfügbar")

    def zentriere_fenster(self):
        """Positioniert das Fenster exakt in der Mitte des Bildschirms."""
        bildschirm = self.screen() or QApplication.primaryScreen()
        geometrie = bildschirm.availableGeometry()
        x = geometrie.x() + (geometrie.width() - self.breite) // 2
        y = geometrie.y() + (geometrie.height() - self.hoehe) // 2
        self.move(x, y)

# *****************************************************************************
# Main
# *****************************************************************************
def main():
    app = QApplication(sys.argv)
    fenster = HauptFenster()
    fenster.zentriere_fenster()
    fenster.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()
# *****************************************************************************
# Ende
# *****************************************************************************


        
🐍 Skript herunterladen (.py)