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}")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章