当前位置: 首页 > news >正文

python脚本实现windows电脑内存监控内存清理(类似rammap清空工作集功能)

import ctypes
import psutil
import time
import sys
import os
from datetime import datetime
import pyautogui# 检查管理员权限
def is_admin():try:return ctypes.windll.shell32.IsUserAnAdmin()except:return False# 内存清理核心功能
def cleanup_memory(aggressiveness=0.5):try:# 获取所有进程processes = psutil.process_iter()# 系统关键进程白名单system_processes = {"System Idle Process", "System", "svchost.exe","wininit.exe", "csrss.exe", "lsass.exe"}# 初始化WinAPIPROCESS_QUERY_INFORMATION = 0x0400PROCESS_SET_QUOTA = 0x0100# 加载 psapi.dllpsapi = ctypes.WinDLL('psapi', use_last_error=True)EmptyWorkingSet = psapi.EmptyWorkingSetEmptyWorkingSet.argtypes = [ctypes.c_void_p]cleaned = 0for proc in processes:try:# 获取进程信息pid = proc.pidname = proc.name()# 跳过系统关键进程和自身if name in system_processes or pid == os.getpid():continue# 尝试获取进程句柄hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SET_QUOTA,False,pid)if hProcess:# 尝试清空工作集if EmptyWorkingSet(hProcess):cleaned += 1ctypes.windll.kernel32.CloseHandle(hProcess)except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):continuereturn cleanedexcept Exception as e:print(f"清理过程中发生错误: {str(e)}")return 0# 内存监控
def memory_monitor(threshold=30, interval=60, aggressiveness=0.5):print("内存监控已启动...")try:while True:mem = psutil.virtual_memory()used_percent = mem.percentprint(f"--------------------\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} \n当前内存使用率: {used_percent}%(自动清理阈值:{threshold}%)")if used_percent > threshold:# print("开始清理内存...")cleaned = cleanup_memory(aggressiveness)print(f"已清理 {cleaned} 个进程的工作集内存...")# 清理后再次检查time.sleep(5)  # 预留清理过程的时间new_mem = psutil.virtual_memory()print(f"清理后内存使用率: {new_mem.percent}%")print(f"累计释放内存: {(mem.used - new_mem.used) // 1024 // 1024} MB")time.sleep(interval)except KeyboardInterrupt:print("\n监控已停止")if __name__ == "__main__":if not is_admin():print("需要管理员权限运行!")ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)sys.exit()# 配置参数config = {'threshold': 30,  # 触发清理的内存使用率阈值(百分比)'interval': 600,  # 检查间隔(秒)'aggressiveness': 0.3  # 清理强度(0.1 ~ 1)}# 内存使用率阈值(百分比)try:config['threshold'] = int(pyautogui.prompt('请输入触发清理的内存使用率阈值-(整数)-(默认30%)!'))except:config['threshold'] = 30print(f"初始参数:\n--自动清理阈值:{config['threshold']}%")# 检查间隔(秒)try:config['interval'] = int(pyautogui.prompt('请设置检查间隔(秒)-(整数)-(默认600秒)!'))except:config['interval'] = 600print(f"--检查间隔:{config['interval']}秒")# 清理强度(0.1~1.0)try:config['aggressiveness'] = float(pyautogui.prompt('请设置清理强度(0.1 ~ 1)-(默认0.3)!'))except:config['aggressiveness'] = 0.3print(f"--清理强度(0.1 ~ 1):{config['aggressiveness']}")# 执行内存监控try:memory_monitor(**config)except Exception as e:print(f"程序发生错误: {str(e)}")

http://www.lryc.cn/news/534318.html

相关文章:

  • 【狂热算法篇】并查集:探秘图论中的 “连通神器”,解锁动态连通性的神秘力量
  • SpringBoot中实现动态数据源切换
  • 数据结构及排序算法
  • Python基础-元组tuple的学习
  • 【手写公式识别】MEMix: Improving HMER with Diverse Formula Structure Augmentation 论文阅读
  • 使用deepseek写一个飞机大战游戏
  • 用Kibana实现Elasticsearch索引的增删改查:实战指南
  • C# 封送和远程编程介绍
  • MybatisPlus较全常用复杂查询引例(limit、orderby、groupby、having、like...)
  • 02.07 TCP服务器与客户端的搭建
  • Jenkins数据备份到windows FTP服务器
  • 【R语言】卡方检验
  • ASP.NET Core托管服务
  • HarmonyOS 5.0应用开发——全局自定义弹出框openCustomDialog
  • 如何在C++ QT 程序中集成cef3开源浏览器组件去显示网页?
  • 深入讲解MyBatis
  • 使用matlab 对传递函数分析bode图和阶跃函数
  • 2025牛客寒假算法基础集训营5(补题)
  • FaceFusion如何设置公开链接和端口
  • 神经网络常见激活函数 6-RReLU函数
  • 计算机网络面经
  • Qt:常用控件
  • 算法设计-找第二大数(C++)
  • 【C++高并发服务器WebServer】-14:Select详解及实现
  • redis项目
  • Spring统一修改RequestBody
  • NCV4275CDT50RKG 车规级LDO线性电压调节器芯片——专为新能源汽车设计的高可靠性电源解决方案
  • 前端开发架构师Prompt指令的最佳实践
  • 【AI实践】Windsurf AI编程voice对话应用
  • 【自学笔记】文言一心的基础知识点总览-持续更新