psutil是个跨平台库,能够轻松实现获取系统运行的进程和系统利用率,包括CPU、内存、磁盘、网络等信息。
它主要应用于信息监控,分析和限制系统资源及进程的管理。它实现了同等命令命令行工具提供的功能,如:ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等。目前支持32位和64位的linux、windows、OS X、FreeBSD和Sun Solaris等操作系统。
(1)源码安装psutil
git clone https://github.com/giampaolo/psutil.gitcd psutilpython3 setup.py install
(2)pip安装
pip3 install psutil
(3)windows上安装
C:/python35/python.exe -m pip install psutil或者源码编译安装:make.bat buildmake.bat install
In [10]: psutil.cpu_times(percpu=False) #查看CPU所有信息Out[10]: scputimes(user=306.98, nice=2.01, system=337.34, idle=410414.39, iowait=78.37, irq=0.0, softirq=17.42, steal=0.0, guest=0.0, guest_nice=0.0)#user:用户进程花费的时间#nice:用户模式执行Niced优先级进程花费的时间#system:内核模式进程花费的时间#idle:闲置时间#iowait:等待I/O完成的时间#irq:处理硬件中断的时间#softirq:处理软件中断的时间#steal:虚拟化环境中运行的其他操作系统花费的时间#guest:在linux内核的控制下为客户端操作系统运行虚拟CPU所花费的时间#guest_nice:虚拟机运行niced所花费的时间
#显示CPU所有逻辑信息
In [7]: psutil.cpu_times(percpu=True) #显示所有CPU逻辑信息Out[7]: [scputimes(user=45.48, nice=0.31, system=69.41, idle=101285.67, iowait=19.67, irq=0.0, softirq=3.06, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=110.04, nice=0.46, system=70.63, idle=101210.2, iowait=22.99, irq=0.0, softirq=5.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=58.5, nice=0.5, system=126.64, idle=100934.59, iowait=14.47, irq=0.0, softirq=4.36, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=92.1, nice=0.72, system=68.3, idle=101146.96, iowait=21.12, irq=0.0, softirq=4.79, steal=0.0, guest=0.0, guest_nice=0.0)]
#显示用户占CPU的时间比
In [11]: psutil.cpu_times().user #显示用户占CPU的时间比Out[11]: 307.11
#显示CPU逻辑个数和物理个数
In [8]: psutil.cpu_count(logical=True) #显示CPU逻辑个数Out[8]: 4In [9]: psutil.cpu_count(logical=False) #显示CPU物理个数Out[9]: 4
#将各种CPU统计信息作为命名元组返回
In [15]: psutil.cpu_stats() #CPU统计信息Out[15]: scpustats(ctx_switches=9838934, interrupts=10572621, soft_interrupts=5582125, syscalls=0)#ctx_switches:启动后的上下问切换次数#interrupts:自启动以来的中断次数#soft_interrupts:启动后的软件中断数量#syscalls:启动以来的系统调用次数,在linux上始终为0
新闻热点
疑难解答