Python獲取系統性能信息
在開發和維護應用程序的過程中,瞭解系統的性能狀態是至關重要的。這不僅可以幫助我們優化程序的運行效率,還可以及時發現並解決潛在的問題。Python 作為一種強大的編程語言,提供了多種方式來獲取系統的性能信息。本文將介紹如何使用 psutil 庫來獲取包括CPU、內存、磁盤和網絡在內的系統性能數據。
安裝 psutil
psutil(Process and System Utilities)是一個跨平台庫,用於檢索有關正在運行的進程和系統利用率(CPU、內存、磁盤、網絡等)的信息。首先,我們需要安裝這個庫:
pip install psutil
獲取 CPU 信息
CPU 使用率
獲取當前的 CPU 使用率非常簡單,可以使用 cpu_percent() 函數:
import psutil
# 獲取當前CPU的使用率
print(f"CPU使用率: {psutil.cpu_percent(interval=1)}%")
CPU 核心數
如果你想了解系統的 CPU 核心數,可以使用 cpu_count() 函數:
# 獲取CPU核心數
print(f"CPU核心數: {psutil.cpu_count(logical=True)}")
獲取 內存 信息
內存使用情況
要獲取內存使用情況,可以使用 virtual_memory() 函數,它返回一個命名元組,包含 total、available、percent、used 和 free 等屬性:
# 獲取內存信息
memory_info = psutil.virtual_memory()
print(f"總內存: {memory_info.total / (1024.0 ** 3):.2f} GB")
print(f"已用內存: {memory_info.used / (1024.0 ** 3):.2f} GB")
print(f"空閒內存: {memory_info.free / (1024.0 ** 3):.2f} GB")
print(f"內存使用率: {memory_info.percent}%")
獲取 磁盤 信息
磁盤分區信息
獲取磁盤分區信息可以使用 disk_partitions() 函數,它會列出所有可用的磁盤分區及其相關信息:
# 獲取磁盤分區信息
for partition in psutil.disk_partitions():
print(f"設備: {partition.device}, 掛載點: {partition.mountpoint}, 文件系統類型: {partition.fstype}")
磁盤使用情況
對於每個磁盤分區,可以使用 disk_usage() 函數來獲取其使用情況:
# 獲取磁盤使用情況
for partition in psutil.disk_partitions():
usage = psutil.disk_usage(partition.mountpoint)
print(f"掛載點: {partition.mountpoint}, 總大小: {usage.total / (1024.0 ** 3):.2f} GB, 已用: {usage.used / (1024.0 ** 3):.2f} GB, 空閒: {usage.free / (1024.0 ** 3):.2f} GB, 使用率: {usage.percent}%")
獲取 網絡 信息
網絡接口信息
獲取網絡接口信息可以使用 net_if_addrs() 函數,它返回一個字典,其中鍵是網絡接口名稱,值是一個地址列表:
# 獲取網絡接口信息
for interface, addrs in psutil.net_if_addrs().items():
for addr in addrs:
print(f"接口: {interface}, 地址: {addr.address}, 子網掩碼: {addr.netmask}, 廣播地址: {addr.broadcast}")
網絡流量統計
要獲取網絡流量統計信息,可以使用 net_io_counters() 函數,它返回一個命名元組,包含發送和接收的數據量:
# 獲取網絡流量統計
net_io = psutil.net_io_counters()
print(f"發送字節數: {net_io.bytes_sent / (1024.0 ** 2):.2f} MB")
print(f"接收字節數: {net_io.bytes_recv / (1024.0 ** 2):.2f} MB")
Python 提供了多種庫來幫助開發者輕鬆地獲取這些信息。其中一個非常強大的庫是 psutil(Process and System Utilities),它是一個跨平台庫,用於檢索有關正在運行的進程和系統利用率(CPU、內存、磁盤、網絡等)的信息。
下面是一些使用 psutil 獲取系統性能信息的基本示例:
1. 安裝 psutil
首先,你需要安裝 psutil 庫。可以通過 pip 安裝:
pip install psutil
2. 獲取 CPU 使用率
import psutil
# 獲取 CPU 使用率
cpu_usage = psutil.cpu_percent(interval=1)
print(f"CPU Usage: {cpu_usage}%")
3. 獲取內存使用情況
import psutil
# 獲取內存信息
memory_info = psutil.virtual_memory()
print(f"Total Memory: {memory_info.total / (1024 ** 3):.2f} GB")
print(f"Available Memory: {memory_info.available / (1024 ** 3):.2f} GB")
print(f"Used Memory: {memory_info.used / (1024 ** 3):.2f} GB")
print(f"Memory Percentage: {memory_info.percent}%")
4. 獲取磁盤使用情況
import psutil
# 獲取磁盤信息
disk_info = psutil.disk_usage('/')
print(f"Total Disk Space: {disk_info.total / (1024 ** 3):.2f} GB")
print(f"Used Disk Space: {disk_info.used / (1024 ** 3):.2f} GB")
print(f"Free Disk Space: {disk_info.free / (1024 ** 3):.2f} GB")
print(f"Disk Usage Percentage: {disk_info.percent}%")
5. 獲取網絡接口信息
import psutil
# 獲取網絡接口信息
net_io = psutil.net_io_counters()
print(f"Bytes Sent: {net_io.bytes_sent}")
print(f"Bytes Received: {net_io.bytes_recv}")
6. 獲取系統啓動時間
import psutil
import datetime
# 獲取系統啓動時間
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
print(f"System Boot Time: {boot_time}")
7. 獲取當前系統所有進程信息
import psutil
# 獲取所有進程信息
for proc in psutil.process_iter(['pid', 'name', 'username']):
print(proc.info)
以上示例展示瞭如何使用 psutil 庫來獲取系統的各種性能信息。這在開發監控工具或需要實時瞭解系統狀態的應用中非常實用。通過這些基礎示例,你可以根據自己的需求進一步擴展功能,例如將這些數據發送到遠程服務器進行集中管理,或者設置閾值警報等。在Python中,可以使用多種庫來獲取系統的性能信息,如CPU使用率、內存使用情況、磁盤I/O等。以下是一些常用的庫及其用法:
1. psutil 庫
psutil 是一個跨平台的庫,用於檢索有關正在運行的進程和系統利用率(CPU、內存、磁盤、網絡等)的信息。
安裝
pip install psutil
示例代碼
獲取CPU信息
import psutil
# 獲取CPU邏輯核心數
cpu_count = psutil.cpu_count(logical=True)
print(f"CPU邏輯核心數: {cpu_count}")
# 獲取CPU物理核心數
cpu_count_physical = psutil.cpu_count(logical=False)
print(f"CPU物理核心數: {cpu_count_physical}")
# 獲取CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU使用率: {cpu_percent}%")
獲取內存信息
# 獲取內存信息
memory_info = psutil.virtual_memory()
print(f"總內存: {memory_info.total / (1024 ** 3):.2f} GB")
print(f"已用內存: {memory_info.used / (1024 ** 3):.2f} GB")
print(f"空閒內存: {memory_info.free / (1024 ** 3):.2f} GB")
print(f"內存使用率: {memory_info.percent}%")
獲取磁盤信息
# 獲取磁盤分區信息
disk_partitions = psutil.disk_partitions()
for partition in disk_partitions:
print(f"設備: {partition.device}")
print(f"掛載點: {partition.mountpoint}")
print(f"文件系統類型: {partition.fstype}")
usage = psutil.disk_usage(partition.mountpoint)
print(f"總空間: {usage.total / (1024 ** 3):.2f} GB")
print(f"已用空間: {usage.used / (1024 ** 3):.2f} GB")
print(f"空閒空間: {usage.free / (1024 ** 3):.2f} GB")
print(f"使用率: {usage.percent}%")
print()
獲取網絡信息
# 獲取網絡接口信息
net_io_counters = psutil.net_io_counters(pernic=True)
for interface, stats in net_io_counters.items():
print(f"接口: {interface}")
print(f"發送字節數: {stats.bytes_sent}")
print(f"接收字節數: {stats.bytes_recv}")
print(f"發送包數: {stats.packets_sent}")
print(f"接收包數: {stats.packets_recv}")
print()
2. os 和 subprocess 庫
雖然 psutil 提供了更高級的功能,但有時你可能需要直接調用系統命令來獲取某些信息。這時可以使用 os 和 subprocess 庫。
示例代碼
獲取系統負載
import os
# 獲取系統負載
load_avg = os.getloadavg()
print(f"系統負載: {load_avg}")
執行系統命令
import subprocess
# 獲取系統信息
result = subprocess.run(['uname', '-a'], capture_output=True, text=True)
print(f"系統信息: {result.stdout}")
3. resource 庫
resource 庫可以用來獲取當前進程的資源使用情況,如CPU時間和內存使用量。
示例代碼
import resource
# 獲取當前進程的資源使用情況
usage = resource.getrusage(resource.RUSAGE_SELF)
print(f"用户CPU時間: {usage.ru_utime:.2f} 秒")
print(f"系統CPU時間: {usage.ru_stime:.2f} 秒")
print(f"最大駐留集大小: {usage.ru_maxrss * 1024} 字節")
這些庫和方法可以幫助你全面地獲取系統的性能信息。根據你的具體需求,可以選擇合適的工具和方法。