电脑应用程序占内存太多怎么办(Python脚本用来检测电脑系统中占用内存较高的进程?)

wufei123 发布于 2024-09-07 阅读(2)

相信很多人都遇到到自己电脑像是发了疯似得运行,而我们根本不知道到底哪些进程占用了很高的CPU内存利用率下面我们就来给出这样一个脚本来检查电脑中占用内存较高的进程脚本实现确保已安装 psutil 库如果尚未安装,可以使用以下命令进行安装。

pip install psutil可以使用 psutil 库来编写一个Python脚本,用于检测系统中占用内存较高的进程,并列出这些进程的进程号,如下所示import psutil defget_high_memory_processes。

(threshold=100):""" 获取占用内存高于指定阈值的进程列表 :param threshold: 内存使用的阈值(MB),默认值为100MB :return: 占用内存较高的进程信息列表,每个元素为一个字典,包含进程ID和内存使用信息。

""" high_memory_processes = [] for proc in psutil.process_iter([pid, name, memory_info]):

try: mem_usage = proc.info[memory_info].rss / (1024 * 1024) # 将内存使用转换为MBif mem_usage > threshold: high_memory_processes.append({

pid: proc.info[pid], name: proc.info[name], memory_usage_MB: mem_usage })

except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): passreturn high_memory_processes

defmain(): threshold = 100# 设置内存使用的阈值(MB) high_memory_processes = get_high_memory_processes(threshold)

if high_memory_processes: print(f"占用内存高于 {threshold}MB 的进程列表:") for proc in high_memory_processes: print(

f"PID: {proc[pid]}, 进程名: {proc[name]}, 内存使用: {proc[memory_usage_MB]:.2f} MB") else: print(

f"没有发现占用内存高于 {threshold}MB 的进程") if __name__ == "__main__": main() 运行这个代码脚本之后,会遇到如下的报错信息,in main high_memory_processes = get_high_memory_processes(threshold) line 。

13, in get_high_memory_processes mem_usage = proc.info[memory_info].rss / (1024 * 1024) # 将内存使用转换为MBAttributeError:

NoneTypeobject has no attribute rss这个错误通常发生在psutil库无法获取进程的内存信息时这可能是因为进程在函数执行期间已经终止或权限不足等原因导致,这种情况在Linux系统中比较常见。

我们可以对程序代码做如下的优化优化代码为了解决这个问题,我们可以在处理AttributeError异常的时候进行合适的处理,例如跳过无法获取内存信息的进程如下所示import psutil defget_high_memory_processes

(threshold=100):""" 获取占用内存高于指定阈值的进程列表 :param threshold: 内存使用的阈值(MB),默认值为100MB :return: 占用内存较高的进程信息列表,每个元素为一个字典,包含进程ID和内存使用信息。

""" high_memory_processes = [] for proc in psutil.process_iter([pid, name, memory_info]):

try: mem_info = proc.info.get(memory_info) if mem_info isnotNone: mem_usage = mem_info.rss / (

1024 * 1024) # 将内存使用转换为MBif mem_usage > threshold: high_memory_processes.append({

pid: proc.info[pid], name: proc.info[name], memory_usage_MB

: mem_usage }) except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):

passreturn high_memory_processes defmain(): threshold = 100# 设置内存使用的阈值(MB) high_memory_processes = get_high_memory_processes(threshold)

if high_memory_processes: print(f"占用内存高于 {threshold}MB 的进程列表:") for proc in high_memory_processes: print(

f"PID: {proc[pid]}, 进程名: {proc[name]}, 内存使用: {proc[memory_usage_MB]:.2f} MB") else: print(

f"没有发现占用内存高于 {threshold}MB 的进程") if __name__ == "__main__": main()在代码修改中通过了proc.info.get(memory_info)来获取进程的内存信息,并在获取到None类型的时候跳过这个进程的获取这样可以避免AttributeError异常。

最终程序就运行就可以获取到占用内存较高的进程,如果是遇到了一些不是太有用的进程的话我们就可以根据进程号进行查杀。

亲爱的读者们,感谢您花时间阅读本文。如果您对本文有任何疑问或建议,请随时联系我。我非常乐意与您交流。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。