溫馨提示×

python psutil如何有效使用

小樊
81
2024-11-19 04:58:34
欄目: 編程語言

Python的psutil庫是一個跨平臺的庫,用于獲取有關(guān)正在運(yùn)行的進(jìn)程和系統(tǒng)利用率(CPU、內(nèi)存、磁盤、網(wǎng)絡(luò)等)的信息

  1. 首先,確保已經(jīng)安裝了psutil庫。如果沒有安裝,可以使用以下命令安裝:
pip install psutil
  1. 導(dǎo)入psutil庫:
import psutil
  1. 獲取系統(tǒng)CPU信息:
cpu_info = psutil.cpu_percent()
print(f"CPU Usage: {cpu_info}%")
  1. 獲取系統(tǒng)內(nèi)存信息:
memory_info = psutil.virtual_memory()
print(f"Total Memory: {memory_info.total / (1024 * 1024)} MB")
print(f"Available Memory: {memory_info.available / (1024 * 1024)} MB")
  1. 獲取磁盤空間信息:
disk_usage = psutil.disk_usage('/')
print(f"Total Disk Space: {disk_usage.total / (1024 * 1024 * 1024)} GB")
print(f"Used Disk Space: {disk_usage.used / (1024 * 1024 * 1024)} GB")
  1. 獲取網(wǎng)絡(luò)接口信息:
net_io = psutil.net_io_counters()
print(f"Bytes Sent: {net_io.bytes_sent}")
print(f"Bytes Received: {net_io.bytes_recv}")
  1. 獲取正在運(yùn)行的進(jìn)程列表:
processes = psutil.process_iter(['pid', 'name', 'cpu_percent'])
for process in processes:
    print(f"PID: {process.info['pid']}, Name: {process.info['name']}, CPU Usage: {process.info['cpu_percent']}%")
  1. 監(jiān)控CPU使用率(例如,每1秒獲取一次CPU使用率):
import time

while True:
    cpu_usage = psutil.cpu_percent()
    print(f"CPU Usage: {cpu_usage}%")
    time.sleep(1)

這只是psutil庫的一些基本用法。您可以根據(jù)需要使用這些功能來監(jiān)控和獲取系統(tǒng)資源信息。要了解更多關(guān)于psutil庫的信息,請查閱官方文檔:https://psutil.readthedocs.io/en/latest/

0