標籤:python linux.shell
psutil模組能夠擷取系統啟動並執行進程和系統利用率。包括:CPU,記憶體,磁碟,網路等資訊。一般用於系統的監控,分析和限制系統資源和進程的管理。
首先下載安裝psutil:
wget https://pypi.python.org/packages/source/p/psutil/psutil-2.0.0.tar.gztar zxvf psutil-2.0.0.tar.gzcd psutil-2.0.0python setup.py install
安裝出錯資訊:
error:command ‘gcc‘ failed with exit status 1
解決方案:
yum install gcc python-devel -y
一、查看記憶體總量和使用量
>>>import psutil>>>mem = psutil.virtual_memory()>>>mem.total,mem.used(1968566272L,371720192L)
二、擷取系統效能資訊
1.cpu資訊
2.User Time:執行使用者進程的時間百分比
3.System Time:執行核心進程和中斷的時間百分比
4.Wait IO 由於IO等待而使CPU處於idle空閑狀態的時間百分比
5.Idle,CPU處於idle狀態的時間百分比
我們使用python的psutil.cpu_times()方法可以簡單的得到這些資訊,同時可以擷取CPU的硬體相關資訊,比如CPU的物理個數和邏輯個數,例子如下:
>>>psutil.cpu_times()scputimes(user=7.9100000000000001,nice=0.0, system=13.41, idle=645.64999999999998, iowait=5.1500000000000004,irq=0.33000000000000002, softirq=0.32000000000000001, steal=0.0, guest=0.0)>>>psutil.cpu_times().user #擷取user的cpu時間比8.0099999999999998>>>psutil.cpu_count() #擷取cpu的邏輯個數1>>>psutil.cpu_count(logical=False) #擷取CPU的物理個數1
#記憶體資訊
>>>mem = psutil.virtual_memory()>>>memsvmem(total=1968566272L,available=1779888128L, percent=9.5999999999999996, used=372531200L,free=1596035072L, active=225411072, inactive=77631488, buffers=10407936L,cached=173445120)>>>mem.total1968566272L>>>mem.free1596035072L>>>psutil.swap_memory()sswap(total=2147479552L,used=0L, free=2147479552L, percent=0.0, sin=0, sout=0)>>>
#磁碟資訊
>>>mem = psutil.disk_partitions()>>>psutil.disk_partitions()[sdiskpart(device=‘/dev/sda3‘,mountpoint=‘/‘, fstype=‘ext4‘, opts=‘rw‘), sdiskpart(device=‘/dev/sda1‘,mountpoint=‘/boot‘, fstype=‘ext4‘, opts=‘rw‘)]>>>psutil.disk_usage(‘/‘)sdiskusage(total=18682343424,used=2136817664, free=15589699584, percent=11.4)>>>psutil.disk_io_counters()sdiskio(read_count=4895,write_count=2763, read_bytes=173164544, write_bytes=44500992, read_time=8461,write_time=12124)>>>
#網路資訊
>>>psutil.net_io_counters()snetio(bytes_sent=708988,bytes_recv=4904912, packets_sent=4577, packets_recv=5314, errin=0, errout=0,dropin=0, dropout=0)>>>psutil.net_io_counters(pernic=True){‘lo‘:snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0,errout=0, dropin=0, dropout=0), ‘eth1‘: snetio(bytes_sent=711716,bytes_recv=4908234, packets_sent=4601, packets_recv=5352, errin=0, errout=0,dropin=0, dropout=0)}
#其他系統資訊
>>>psutil.users()[suser(name=‘root‘,terminal=‘pts/0‘, host=‘192.168.1.5‘, started=1434034432.0)]>>>psutil.boot_time()1434034443.0
本文出自 “梁恩宇-9527” 部落格,轉載請與作者聯絡!
python系統資訊模組psutil