Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import psutil
- import os
- import logging
- from PyQt5.QtWidgets import (
- QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel,
- QPushButton, QHBoxLayout, QTableWidget, QTableWidgetItem,
- QHeaderView, QFrame
- )
- from PyQt5.QtCore import QTimer, Qt
- from PyQt5.QtGui import QFont, QPalette, QColor, QIcon
- # Настройка логирования
- logging.basicConfig(
- filename="resource_allocator.log",
- level=logging.ERROR,
- format="%(asctime)s - %(levelname)s - %(message)s",
- )
- class DarkTheme:
- @staticmethod
- def setup(app):
- palette = QPalette()
- palette.setColor(QPalette.Window, QColor(53, 53, 53))
- palette.setColor(QPalette.WindowText, Qt.white)
- palette.setColor(QPalette.Base, QColor(35, 35, 35))
- palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
- palette.setColor(QPalette.ToolTipBase, Qt.white)
- palette.setColor(QPalette.ToolTipText, Qt.white)
- palette.setColor(QPalette.Text, Qt.white)
- palette.setColor(QPalette.Button, QColor(53, 53, 53))
- palette.setColor(QPalette.ButtonText, Qt.white)
- palette.setColor(QPalette.BrightText, Qt.red)
- palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
- palette.setColor(QPalette.HighlightedText, Qt.black)
- app.setPalette(palette)
- app.setStyleSheet("""
- QMainWindow {
- background-color: #353535;
- }
- QLabel {
- color: white;
- }
- QPushButton {
- background-color: #454545;
- border: 1px solid #555;
- padding: 8px;
- min-width: 120px;
- color: white;
- }
- QPushButton:hover {
- background-color: #555;
- }
- QPushButton:pressed {
- background-color: #353535;
- }
- QPushButton:disabled {
- color: #888;
- }
- QTableWidget {
- background-color: #252525;
- border: 1px solid #444;
- gridline-color: #444;
- color: white;
- }
- QHeaderView::section {
- background-color: #353535;
- padding: 5px;
- border: none;
- color: white;
- }
- QTableWidget::item {
- border-bottom: 1px solid #444;
- }
- """)
- class ResourceAllocatorApp(QMainWindow):
- def __init__(self):
- super().__init__()
- self.setWindowTitle("Resource Allocator")
- self.setGeometry(100, 100, 900, 700)
- self.max_cores = os.cpu_count()
- self.is_active_mode = False
- self.init_ui()
- self.timer = QTimer()
- self.timer.timeout.connect(self.update_processes)
- self.timer.start(1000)
- def init_ui(self):
- main_widget = QWidget()
- main_layout = QVBoxLayout(main_widget)
- main_layout.setContentsMargins(20, 20, 20, 20)
- main_layout.setSpacing(15)
- # Заголовок
- header = QLabel("Resource Allocator")
- header.setFont(QFont("Arial", 18, QFont.Bold))
- header.setAlignment(Qt.AlignCenter)
- main_layout.addWidget(header)
- # Панель информации
- info_frame = QFrame()
- info_frame.setFrameShape(QFrame.StyledPanel)
- info_layout = QVBoxLayout(info_frame)
- info_layout.setContentsMargins(15, 15, 15, 15)
- self.mode_label = QLabel("Режим: Стандартный планировщик Windows")
- self.mode_label.setFont(QFont("Arial", 12, QFont.Bold))
- self.core_label = QLabel(f"Всего ядер в системе: {self.max_cores}")
- self.core_label.setFont(QFont("Arial", 11))
- info_layout.addWidget(self.mode_label)
- info_layout.addWidget(self.core_label)
- main_layout.addWidget(info_frame)
- # Кнопки управления
- btn_frame = QFrame()
- btn_layout = QHBoxLayout(btn_frame)
- btn_layout.setContentsMargins(0, 0, 0, 0)
- self.btn_enable = QPushButton("Включить все ядра")
- self.btn_enable.setFont(QFont("Arial", 11))
- self.btn_enable.clicked.connect(self.enable_all_cores)
- self.btn_enable.setFixedHeight(40)
- self.btn_disable = QPushButton("Выключить (стандартный режим)")
- self.btn_disable.setFont(QFont("Arial", 11))
- self.btn_disable.clicked.connect(self.disable_all_cores)
- self.btn_disable.setFixedHeight(40)
- self.btn_disable.setEnabled(False)
- btn_layout.addWidget(self.btn_enable)
- btn_layout.addWidget(self.btn_disable)
- main_layout.addWidget(btn_frame)
- # Таблица процессов
- self.process_table = QTableWidget()
- self.process_table.setColumnCount(3)
- self.process_table.setHorizontalHeaderLabels(["Процесс", "PID", "Режим ядер"])
- self.process_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
- self.process_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
- self.process_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
- self.process_table.setFont(QFont("Arial", 10))
- self.process_table.setAlternatingRowColors(True)
- main_layout.addWidget(self.process_table)
- self.setCentralWidget(main_widget)
- def enable_all_cores(self):
- self.is_active_mode = True
- for proc in psutil.process_iter(['pid']):
- try:
- proc.cpu_affinity(list(range(self.max_cores)))
- except (psutil.NoSuchProcess, psutil.AccessDenied):
- continue
- self.mode_label.setText("Режим: Все процессы используют все ядра")
- self.btn_enable.setEnabled(False)
- self.btn_disable.setEnabled(True)
- def disable_all_cores(self):
- self.is_active_mode = False
- for proc in psutil.process_iter(['pid']):
- try:
- proc.cpu_affinity(list(range(self.max_cores)))
- except (psutil.NoSuchProcess, psutil.AccessDenied):
- continue
- self.mode_label.setText("Режим: Стандартный планировщик Windows")
- self.btn_enable.setEnabled(True)
- self.btn_disable.setEnabled(False)
- def update_processes(self):
- if self.is_active_mode:
- self.enable_all_cores()
- self.update_process_table()
- def update_process_table(self):
- try:
- processes = []
- for proc in psutil.process_iter(['pid', 'name', 'cpu_affinity']):
- try:
- processes.append({
- 'name': proc.info['name'],
- 'pid': proc.info['pid'],
- 'cores': len(proc.info['cpu_affinity']) if proc.info['cpu_affinity'] else 0
- })
- except (psutil.NoSuchProcess, psutil.AccessDenied):
- continue
- processes.sort(key=lambda x: x['name'])
- self.process_table.setRowCount(len(processes))
- for row, proc in enumerate(processes):
- self.process_table.setItem(row, 0, QTableWidgetItem(proc['name']))
- self.process_table.setItem(row, 1, QTableWidgetItem(str(proc['pid'])))
- # Измененное отображение информации о ядрах
- if self.is_active_mode:
- core_text = f"Использует {proc['cores']} ядер" if proc['cores'] > 0 else "Нет доступа"
- else:
- core_text = "Стандартный режим Windows"
- self.process_table.setItem(row, 2, QTableWidgetItem(core_text))
- except Exception as e:
- logging.error(f"Ошибка при обновлении таблицы: {e}")
- def handle_exception(exc_type, exc_value, exc_traceback):
- logging.error("Неперехваченное исключение", exc_info=(exc_type, exc_value, exc_traceback))
- if __name__ == "__main__":
- app = QApplication(sys.argv)
- DarkTheme.setup(app)
- window = ResourceAllocatorApp()
- window.show()
- sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement