1. 程式人生 > 實用技巧 >psutil: 資源監控

psutil: 資源監控

廢話

這篇文章是之前,寫在有道雲上的,當時的目的就是 使用socket 與psutil 實現 locust工具效能測試時的伺服器資源監控

# 官方文件:https://psutil.readthedocs.io/en/latest/
# github: https://github.com/giampaolo/psutil

# 匯入python的運維庫
import psutil
# cpu 邏輯數量
cpu_number = psutil.cpu_count()

# cpu 物理核心
cpu_core = psutil.cpu_count(logical=False)

# cpu 的使用者/系統/空閒時間
cpu_time = psutil.cpu_times()

# 每秒重新整理一次cpu使用者/系統/空閒時間
sends_cpu_time = psutil.cpu_percent(interval=1, percpu=True)

# 獲取實體記憶體資訊
virtual_memory = psutil.virtual_memory()

# 獲取交換記憶體資訊
swap_memory = psutil.swap_memory()

# 獲取磁碟資訊
psutil.disk_partitions()  # 磁碟分割槽

psutil.disk_usage('/')  # 磁碟使用情況

psutil.disk_io_counters()  # 磁碟IO

# 獲取網路資訊
psutil.net_io_counters()  # 獲取網路讀寫位元組/包的個數

psutil.net_if_addrs()  # 獲取網路介面資訊

psutil.net_if_stats()  # 獲取網路介面狀態

psutil.net_connections()  # 獲取當前網路資訊

# 獲取程序資訊
psutil.pids()  # 所有程序ID

p = psutil.Process(3776)  # 獲取指定程序ID=3776

p.name()  # 程序名稱

p.exe()  # 程序exe路徑

p.cwd()  # 程序工作目錄

p.cmdline()  # 程序啟動的命令列

p.ppid()  # 父程序ID

p.parent()  # 父程序

p.children()  # 子程序列表

p.status()  # 程序狀態

p.username()  # 程序使用者名稱

p.create_time()  # 程序建立時間

p.terminal()  # 程序終端

p.cpu_times()  # 程序使用的CPU時間

p.memory_info()  # 程序使用的記憶體

p.open_files()  # 程序開啟的檔案

p.connections()  # 程序相關網路連線

p.num_threads()  # 程序的執行緒數量

p.threads()  # 所有執行緒資訊

p.environ()  # 程序環境變數

p.terminate()   # 結束程序

psutil.test()  # 列出所有程序