廢話不多說。直接整:
我們需要使用psutil 這個第三方庫:直接pip 安裝一下
pip install psutil
然後獲取CPU內存信息代碼如下:
import psutil
def cpuInfo():
cpuTimes = psutil.cpu_times()
# 獲取CPU信息中的內存信息
def memoryInfo(memory):
print(memory)
return {
'總內存(total)': str(round((float(memory.total) / 1024 / 1024 / 1024), 2)) + "G",
'已使用(used)': str(round((float(memory.used) / 1024 / 1024 / 1024), 2)) + "G",
'空閒(free)': str(round((float(memory.free) / 1024 / 1024 / 1024), 2)) + "G",
'使用率(percent)': str(memory.percent) + '%',
'可用(available)': (memory.available) if hasattr(memory, 'available') else '',
'活躍(active)': (memory.active) if hasattr(memory, 'active') else '',
'非活躍(inactive)': (memory.inactive) if hasattr(memory, 'inactive') else '',
'內核使用(wired)': (memory.wired) if hasattr(memory, 'wired') else ''
}
return {
'物理CPU個數': psutil.cpu_count(logical=False),
'邏輯CPU個數': psutil.cpu_count(),
'CPU使用情況': psutil.cpu_percent(percpu=True),
'虛擬內存': memoryInfo(psutil.virtual_memory()),
'交換內存': memoryInfo(psutil.swap_memory()),
'系統啓動到當前時刻': {
pro: getattr(cpuTimes, pro) for pro in dir(cpuTimes) if pro[0:1] != '_' and pro not in ('index', 'count')
},
}
if __name__ == '__main__':
computer_info = cpuInfo()
print(computer_info)
Windows 上運行結果如下:
svmem(total=17129988096, available=9869836288, percent=42.4, used=7260151808, free=9869836288)
sswap(total=18203729920, used=8945336320, free=9258393600, percent=49.1, sin=0, sout=0)
{'物理CPU個數': 4, '邏輯CPU個數': 4, 'CPU使用情況': [0.0, 0.0, 0.0, 0.0], '虛擬內存': {'總內存(total)': '15.95G', '已使用(used)': '6.76G', '空閒(free)': '9.19G', '使用率(percent)': '42.4%', '可用(available)': 9869836288, '活躍(active)': '', '非活躍(inactive)': '', '內核使用(wired)': ''}, '交換內存': {'總內存(total)': '16.95G', '已使用(used)': '8.33G', '空閒(free)': '8.62G', '使用率(percent)': '49.1%', '可用(available)': '', '活躍(active)': '', '非活躍(inactive)': '', '內核使用(wired)': ''}, '系統啓動到當前時刻': {'dpc': 47.234375, 'idle': 18348.3125, 'interrupt': 89.890625, 'system': 2117.0625, 'user': 2326.578125}}
Centos上運行如下圖:
兩者會有些區別,區別在於雲服務器和物理機實際的內存CPU情況。你們都懂得。