Дополнено 0 минут спустя
теперь при включении пк открывается блокнот и там это
import psutil
import mobase
import os
import winreg
import time
from typing import List, Union
try:
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QMessageBox
# Code specific to MO 2.5.0 and above
except ImportError:
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QMessageBox
# Code specific to MO 2.4.4 and below
class AnomalyCPUAffinity(mobase.IPluginTool):
def __init__(self):
super().__init__()
self.__organizer: Union[mobase.IOrganizer, None] = None
self.__parentWidget: Union[QWidget, None] = None
def init(self, organizer: mobase.IOrganizer):
self.__organizer = organizer
self.__add_to_startup() # Добавляем скрипт в автозагрузку при инициализации
self.__start_background_monitor() # Запускаем фоновый мониторинг процессов
return True
def name(self) -> str:
return "AnomalyCPUAffinity"
def author(self) -> str:
return "GaRRuSS"
def description(self) -> str:
return "Set optimal CPU affinity for Anomaly.exe"
def version(self) -> mobase.VersionInfo:
return mobase.VersionInfo(1, 0, 0, mobase.ReleaseType.FINAL)
def isActive(self) -> bool:
return self.__organizer.pluginSetting(self.name(), "enabled") is True
def settings(self) -> List[mobase.PluginSetting]:
return [mobase.PluginSetting("enabled", "enable this plugin", True)]
def displayName(self) -> str:
return "Anomaly CPU Affinity"
def tooltip(self) -> str:
return "Set optimal CPU affinity for Anomaly.exe"
def icon(self) -> QIcon:
return QIcon()
def setParentWidget(self, widget: QWidget) -> None:
self.__parentWidget = widget
def __add_to_startup(self):
"""
Добавляет скрипт в автозагрузку Windows, если его там ещё нет.
"""
try:
# Путь к текущему скрипту
script_path = os.path.abspath(__file__)
# Открываем ключ автозагрузки в реестре
key = winreg.HKEY_CURRENT_USER
key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
with winreg.OpenKey(key, key_path, 0, winreg.KEY_READ | winreg.KEY_WRITE) as reg_key:
try:
# Проверяем, есть ли уже запись в автозагрузке
winreg.QueryValueEx(reg_key, "AnomalyCPUAffinity")
except FileNotFoundError:
# Если записи нет, добавляем её
winreg.SetValueEx(reg_key, "AnomalyCPUAffinity", 0, winreg.REG_SZ, script_path)
print("Скрипт добавлен в автозагрузку.")
except Exception as e:
print(f"Ошибка при добавлении в автозагрузку: {e}")
def __start_background_monitor(self):
"""
Запускает фоновый мониторинг процессов Anomaly.
"""
import threading
# Запускаем мониторинг в отдельном потоке
monitor_thread = threading.Thread(target=self.__monitor_processes, daemon=True)
monitor_thread.start()
def __monitor_processes(self):
"""
Мониторит процессы и устанавливает CPU affinity для Anomaly.
"""
while True:
self.__set_cpu_affinity()
time.sleep(5) # Проверяем процессы каждые 5 секунд
def __set_cpu_affinity(self):
"""
Устанавливает CPU affinity для процессов Anomaly.
"""
# Specify the name of the target executable
target_exe = ["AnomalyDX11AVX.exe", "AnomalyDX11.exe", "AnomalyDX10AVX.exe", "AnomalyDX10.exe",
"AnomalyDX9AVX.exe", "AnomalyDX9.exe", "AnomalyDX8AVX.exe", "AnomalyDX8.exe"]
# Determine logical and physical amount of cores
logical_cores = psutil.cpu_count(logical=True)
physical_cores = psutil.cpu_count(logical=False)
# List available cores depending on cpu type
if logical_cores == physical_cores:
available_cores = list(range(1, physical_cores))
else:
available_cores = list(range(2, (logical_cores - physical_cores) * 2))
# Filter function to search for processes starting with "Anomaly"
def filter_processes(process):
return process.name().startswith('Anomaly')
# Find the process ID (PID) of the target executable starting with "Anomaly"
for process in filter(filter_processes, psutil.process_iter(['pid', 'name'])):
# Check if the target executable is among the filtered processes
if process.name() in target_exe:
pid = process.pid
target_exe_name = process.name()
# Set the CPU affinity of the process to the available cores
psutil.Process(pid).cpu_affinity(available_cores)
# Debug line below
# QMessageBox.information(self.__parentWidget, "Success", f"Done! CPU affinity of {target_exe_name} is set correctly. Physical Cores: {physical_cores} Logical Cores: {logical_cores}")
break
def display(self) -> None:
"""
Основная функция, которая запускается при выборе плагина в MO2.
"""
# Устанавливаем CPU affinity
self.__set_cpu_affinity()
def createPlugin() -> mobase.IPlugin:
return AnomalyCPUAffinity()