一、系统性能信息模块psutil
psutil是一个跨平台库(https://pypi.python.org/pypi/psutil)轻松获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等),能实现ps、top、lso、nice、netstat、ifconfig、who、df、kill、free、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap 这些命令的功能。
1.导入模块
首先确定下当前系统有没有psutil模块
import psutil
如果有的话,就直接导入模块成功,如果没有,就会提示错误
然后到官网上下载psutil-4.1.0.tar.gz源码包
tar -zxf psutil-4.1.0.tar.gz
cd psutil-4.1.0
python setup.py install
2.获取CPU信息
Linux操作系统的CPU利用率有以下几个部分
- User TIme 执行用户进程的时间百分比
- System Time 执行内核进程和中断的时间百分比
- Wait IO 由于IO等待而使CPU处于idle状态时间百分比
- Idle CPU处于idle状态时间百分比
读取cpu的整个信息
import psutil
psutil.cpu_times() #显示cpu的整个信息
获取单项值
psutil.cpu_times() .user #如果要只但看那个的话就在后边加上.xxx就行了
获取cpu的逻辑个数
psutil.cpu_count()
获取cpu的物理个数
psutil.cpu_count( logical=False )
3.获取内存信息
Linux涉及内存利用率信息涉及
- total 内存总数
- used 以及使用的内存数
- free 空闲内存数
- buffers 缓冲内存数
- cache 缓存内存数
- swap 交换分区
分别用psutil.virtual_memory() psutil.swap_memory()方法获取这些新消息
读取内存信息
linux系统内存利用率信息涉及to-tal(内存总数),used(以使用内存),free(空闲内存),buffers(缓冲使用数)
cache(缓存使用数),swap(交换分区使用数),分别使用psutil.virtual_memory()与psuti.swap_memory()方法获取
import psuti
mem = psuti.virtual_memory() #获取内存的完整信息
mem.total #获取内存总数
mem.free #获取空闲的内存信息
获取swap分区信息
psutil.swap_memory()
4.硬盘信息
系统的磁盘信息我们更加关注磁盘的利用率及IO信息,磁盘的利用率使用psutil.disk_usage()方法获取;IO信息包括read_count(读IO数)、write_conut(写IO数)、read_bytes(IO读字节数)、write_bytes(IO写字节数)、read_time(磁盘读时间)、write_time(磁盘写时间)等这些IO信息使用psutil.disk_io_conuters()获取。
读取磁盘参数
磁盘利用率使用psutil.disk_usage方法获取,磁盘IO信息包括read_count(读IO数),write_count(写IO数)
read_bytes(IO写字节数),read_time(磁盘读时间),write_time(磁盘写时间),这些IO信息用psutil.disk_io_counters()
获取磁盘的完整信息
psutil.disk_partitions()
获取分区表的参数
psutil.disk_usage('/') #获取/分区的状态
获取硬盘IO总个数
psutil.disk_io_counters()
获取单个分区IO个数
psutil.disk_io_counters(perdisk=True) #perdisk=True参数获取单个分区IO个数
5.网络信息
读取网络信息
网络信息与磁盘IO信息类似,涉及到几个关键点,包括byes_sent(发送字节数),byte_recv=xxx(接受字节数),
pack-ets_sent=xxx(发送字节数),pack-ets_recv=xxx(接收数据包数),这些网络信息用psutil.net_io_counters()
psutil.net_io_counters() #获取网络总IO信息
psutil.net_io_counters(pernic=True) #pernic=True输出网络每个接口信息
6.其他信息
获取当前系统用户登录信息
psutil.users()
获取开机时间
import psutil, datetime
psutil.boot_time() #以linux时间格式返回
datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S") #转换成自然时间格式
二、进程管理
获取当前系统的进程信息,获取当前英语程序的运行状态,包括进程的启动时间,查看设置CPU亲和度,内存使用率,IO信息
socket连接,线程数等
获取进程信息
psutil模块在获取进程方面有很好的支持,使用psutil.pids()方法获取所有进程的PID,
使用psutil.Process()方法获取单个进程的名称,路径状态等
查看系统全部进程
psutil.pids()
查看单个进程
p = psutil.Process(2423)
p.name() #进程名
p.exe() #进程的bin路径
p.cwd() #进程的工作目录绝对路径
p.status() #进程状态
p.create_time() #进程创建时间
p.uids() #进程uid信息
p.gids() #进程的gid信息
p.cpu_times() #进程的cpu时间信息,包括user,system两个cpu信息
p.cpu_affinity() #get进程cpu亲和度,如果要设置cpu亲和度,将cpu号作为参考就好
p.memory_percent() #进程内存利用率
p.memory_info() #进程内存rss,vms信息
p.io_counters() #进程的IO信息,包括读写IO数字及参数
p.connectios() #返回进程列表
p.num_threads() #进程开启的线程数
听过psutil的Popen方法启动应用程序,可以跟踪程序的相关信息
from subprocess import PIPE
p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"],stdout=PIPE)
p.name()
p.username()
例如:Python获取CPU使用率、内存使用率、网络使用状态(摘自一个Python爱好者)
#
# Copyright (c) 2014, Lambo Wang, All rights reserved.
# Use of this source code is governed by a GNU v2 license that can be
# found in the LICENSE file.
#
# Logs:
# Transplant to system by Lambo Wang, 2012-11-28
# Add function of get cpu state and get memory state by Lambo Wang,2012-11-29
# first add to Git of OSChina,2014-10-24 by Lambo Wang
# support for psutil(v3.2.2),2015-11-12 by Lambo Wang
"""
Shows real-time system statistics.
Author: Lambo Wang <[email protected]>
"""
import sys
import os
import atexit
import time
import psutil
#print "Welcome,current system is",os.name," 3 seconds late start to get data..."
time.sleep(3)
line_num = 1
#function of Get CPU State;
def getCPUstate(interval=1):
return (" CPU: " + str(psutil.cpu_percent(interval)) + "%")
#function of Get Memory
def getMemorystate():
phymem = psutil.virtual_memory()
line = "Memory: %5s%% %6s/%s"%(
phymem.percent,
str(int(phymem.used/1024/1024))+"M",
str(int(phymem.total/1024/1024))+"M"
)
return line
def bytes2human(n):
"""
>>> bytes2human(10000)
'9.8 K'
>>> bytes2human(100001221)
'95.4 M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s' % (value, s)
return '%.2f B' % (n)
def poll(interval):
"""Retrieve raw stats within an interval window."""
tot_before = psutil.net_io_counters()
pnic_before = psutil.net_io_counters(pernic=True)
# sleep some time
time.sleep(interval)
tot_after = psutil.net_io_counters()
pnic_after = psutil.net_io_counters(pernic=True)
# get cpu state
cpu_state = getCPUstate(interval)
# get memory
memory_state = getMemorystate()
return (tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state)
def refresh_window(tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state):
if os.name == 'nt':
os.system("cls")
else:
os.system("clear")
"""Print stats on screen."""
#print current time #cpu state #memory
print(time.asctime()+" | "+cpu_state+" | "+memory_state)
# totals
print(" NetStates:")
print("total bytes: sent: %-10s received: %s" % (bytes2human(tot_after.bytes_sent),
bytes2human(tot_after.bytes_recv))
)
print("total packets: sent: %-10s received: %s" % (tot_after.packets_sent,
tot_after.packets_recv)
)
# per-network interface details: let's sort network interfaces so
# that the ones which generated more traffic are shown first
print("")
nic_names = pnic_after.keys()
#nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
for name in nic_names:
stats_before = pnic_before[name]
stats_after = pnic_after[name]
templ = "%-15s %15s %15s"
print(templ % (name, "TOTAL", "PER-SEC"))
print(templ % (
"bytes-sent",
bytes2human(stats_after.bytes_sent),
bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
))
print(templ % (
"bytes-recv",
bytes2human(stats_after.bytes_recv),
bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
))
print(templ % (
"pkts-sent",
stats_after.packets_sent,
stats_after.packets_sent - stats_before.packets_sent,
))
print(templ % (
"pkts-recv",
stats_after.packets_recv,
stats_after.packets_recv - stats_before.packets_recv,
))
print("")
try:
interval = 0
while 1:
args = poll(interval)
refresh_window(*args)
interval = 1
except (KeyboardInterrupt, SystemExit):
pass