python列出centos7内存使用前50的进程信息

python 代码,列出 centos7系统 内存使用排名前50的进程信息,

按照内存使用大小从大到小排序。

 

import psutil  
  
# 获取系统内存信息  
total_memory = psutil.virtual_memory().total / (1024.0 ** 3)  # 转换为GB  
available_memory = psutil.virtual_memory().available / (1024.0 ** 3)  # 转换为GB  
memory_percent = psutil.virtual_memory().percent  
  
print(f"Total Memory: {total_memory:.2f} GB")  
print(f"Available Memory: {available_memory:.2f} GB")  
print(f"Memory Usage: {memory_percent}%")  
  
# 获取进程信息并按内存使用量排序  
processes = []  
for proc in psutil.process_iter(['pid', 'name']):  
    try:  
        # 获取进程的内存信息  
        memory_info = proc.memory_info()  
        memory_usage = memory_info.rss / (1024.0 ** 2)  # 转换为MB  
        memory_percent = proc.memory_percent()  # 获取内存使用率  
        processes.append((proc.info['pid'], proc.info['name'], memory_usage, memory_percent))  
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):  
        pass  
  
# 排序进程(按内存使用量降序)  
sorted_processes = sorted(processes, key=lambda process: process[2], reverse=True)  
  
# 打印前50个进程  
for proc in sorted_processes[:50]:  
    pid, name, memory_usage, memory_percent = proc  
    print(f"PID: {pid}, Memory Usage: {memory_usage:.2f} MB, Percent: {memory_percent:.3f}%, Name: {name}")

 

posted @ 2024-05-15 13:51  He_LiangLiang  阅读(6)  评论(0编辑  收藏  举报