psutil模块能够获取系统运行的进程和系统利用率。包括:CPU,内存,磁盘,网络等信息。一般用于系统的监控,分析和限制系统资源和进程的管理。
首先下载安装psutil:
wget https://pypi.python.org/packages/source/p/psutil/psutil-2.0.0.tar.gz tar zxvf psutil-2.0.0.tar.gz cd psutil-2.0.0 python 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() >>>mem svmem(total=1968566272L,available=1779888128L, percent=9.5999999999999996, used=372531200L,free=1596035072L, active=225411072, inactive=77631488, buffers=10407936L,cached=173445120) >>>mem.total 1968566272L >>>mem.free 1596035072L >>>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” 博客,转载请与作者联系!
原文地址:http://liangey.blog.51cto.com/9097868/1662161