1. 程式人生 > >Python獲取計算機記憶體硬碟CPU資訊

Python獲取計算機記憶體硬碟CPU資訊

匯入psutil模組

import psutil

獲取CPU資訊

#獲取CPU資訊
@staticmethod
def GetCpuInfo():
    cpu_count = psutil.cpu_count(logical=False)  #1代表單核CPU,2代表雙核CPU  
    xc_count = psutil.cpu_count()                #執行緒數,如雙核四執行緒
    cpu_slv = round((psutil.cpu_percent(1)), 2)  # cpu使用率
    list = [cpu_count,xc_count,cpu_slv]
    return list

獲取記憶體資訊

#獲取記憶體資訊
@staticmethod
def GetMemoryInfo():
    memory = psutil.virtual_memory()
    total_nc = round(( float(memory.total) / 1024 / 1024 / 1024), 2)  # 總記憶體
    used_nc = round(( float(memory.used) / 1024 / 1024 / 1024), 2)  # 已用記憶體
    free_nc = round(( float(memory.free) / 1024 / 1024 / 1024), 2)  # 空閒記憶體
    syl_nc = round((float(memory.used) / float(memory.total) * 100), 2)  # 記憶體使用率

    ret_list = [total_nc,used_nc,free_nc,syl_nc]
    return ret_list

獲取硬碟資訊 

#獲取硬碟資訊
@staticmethod
def GetDiskInfo():
    list = psutil.disk_partitions() #磁碟列表
    ilen = len(list) #磁碟分割槽個數
    i=0
    retlist1=[]
    retlist2=[]
    while i< ilen:
        diskinfo = psutil.disk_usage(list[i].device)
        total_disk = round((float(diskinfo.total)/1024/1024/1024),2) #總大小
        used_disk = round((float(diskinfo.used) / 1024 / 1024 / 1024), 2) #已用大小
        free_disk = round((float(diskinfo.free) / 1024 / 1024 / 1024), 2) #剩餘大小
        syl_disk = diskinfo.percent

        retlist1=[i,list[i].device,total_disk,used_disk,free_disk,syl_disk]  #序號,磁碟名稱,
        retlist2.append(retlist1)  
        i=i+1

    return retlist2