系統性能信息模塊 psutil

用於分析系統資源的工具, 如CPU, 內存,磁盤,網絡等

參考文檔 <https://www.liaoxuefeng.com/wiki/1016959663602400/1183565811281984&gt; 或 python自動化運維 技術與最佳實踐

安裝

pip install psutil 

使用

導入模塊 import psutil

查看內存

# 查看內存狀態
mem = psutil.virtual_memory()   # 單位長度 字節   轉換需要除以三次 (k m g)
# svmem(total=13958176768, available=8882548736, percent=36.4, used=5075628032, free=8882548736)

# round 四捨五入,  獲取2位長度,
total = round(mem.total / 1024 / 1024 / 1024, 2)
print(total)

查看CPU

# 獲取 CPU 邏輯個數
cpuCount = psutil.cpu_count()     # 4

# 獲取 CPU 物理個數
print(psutil.cpu_count(logical=False))   # 4

# percpu=True 顯示所有CPU 運行的所有時間
cpuTime = psutil.cpu_times(percpu=True)
print(cpuTime)

查看磁盤

# 查看磁盤格式以及掛載點
print(psutil.disk_partitions())
# [sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'),
#         sdiskpart(device='D:\\', mountpoint='D:\\', fstype='UDF', opts='ro,cdrom')]

# 查看具體的磁盤大小以及使用情況
print(psutil.disk_usage('C:\\'))
# sdiskusage(total=34252779520, used=25038110720, free=9214668800, percent=73.1)

# 循環出磁盤格式爲NTFS的 == windows機器, percent使用的百分比
for device in psutil.disk_partitions():
    if device.fstype == "NTFS":
        print(psutil.disk_usage(device.device).percent)

查看網絡連接數

# 所有的連接
psutil.net_connections()

查看進程

>>> psutil.pids() # 所有進程ID
[3865, 3864, 3863, 3856, 3855, 3853, 3776, ..., 45, 44, 1, 0]
>>> p = psutil.Process(3776) # 獲取指定進程ID=3776,其實就是當前Python交互環境
>>> p.name() # 進程名稱
'python3.6'
>>> p.exe() # 進程exe路徑
'/Users/michael/anaconda3/bin/python3.6'
>>> p.cwd() # 進程工作目錄
'/Users/michael'
>>> p.cmdline() # 進程啓動的命令行
['python3']
>>> p.ppid() # 父進程ID
3765
>>> p.parent() # 父進程
<psutil.Process(pid=3765, name='bash') at 4503144040>
>>> p.children() # 子進程列表
[]
>>> p.status() # 進程狀態
'running'
>>> p.username() # 進程用戶名
'michael'
>>> p.create_time() # 進程創建時間
1511052731.120333
>>> p.terminal() # 進程終端
'/dev/ttys002'
>>> p.cpu_times() # 進程使用的CPU時間
pcputimes(user=0.081150144, system=0.053269812, children_user=0.0, children_system=0.0)
>>> p.memory_info() # 進程使用的內存
pmem(rss=8310784, vms=2481725440, pfaults=3207, pageins=18)
>>> p.open_files() # 進程打開的文件
[]
>>> p.connections() # 進程相關網絡連接
[]
>>> p.num_threads() # 進程的線程數量
1
>>> p.threads() # 所有線程信息
[pthread(id=1, user_time=0.090318, system_time=0.062736)]
>>> p.environ() # 進程環境變量
{'SHELL': '/bin/bash', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...', 'PWD': '/Users/michael', 'LANG': 'zh_CN.UTF-8', ...}
>>> p.terminate() # 結束進程
Terminated: 15 <-- 自己把自己結束了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章