前言
最近需要一个可以实时访问系统信息的模块,网上搜索以后,发现了psutil可以大致满足我的要求。
psutil简介
psutil(Python system and process utilities)是一个跨平台的进程管理和系统工具的python库,可以处理系统CPU,memory,disks,network等信息。主要用于系统资源的监控,分析,以及对进程进行一定的管理。通过psutil可以实现如ps
,top
,lsof
,netstat
,ifconfig
, who
,df
,kill
,free
,nice
,ionice
,iostat
,iotop
,uptime
,pidof
,tty
,taskset
,pmap
。在Linux,windows,OSX,freebsdSun,Solaris等系统上工作,最新的版本python是要高于2.6(Python 2.4 Python2.5 可以用2.1.3版本)
安装
首先确定下当前系统有没有psutil模块
|
|
如果有的话,就直接导入模块成功,如果没有,就会提示错误然后到官网上下载psutil-2.0.0.tar.gz源码包
|
|
也可以直接使用pip install psutil 来安装
系统相关功能
CPU信息
cpu_times
|
|
返回系统CPU运行时间的元组,时间为秒。
cpu_percent
|
|
返回一个浮点数,代表当前cpu的利用率的百分比,包括sy+user. 当interval
为0或者None时,表示的是interval时间内的sys的利用率。 当percpu
为True返回是每一个cpu的利用率。
cpu_count
|
|
返回CPU的逻辑个数
|
|
返回CPU的物理个数
内存
|
|
返回一个内存信息的元组,大小为字节
- total: 内存的总大小.
- available: 可以用来的分配的内存,不同系统计算方式不同; Linux下的计算公式:free+ buffers +cached
- percent: 已经用掉内存的百分比 (total - available) / total 100.
- used: 已经用掉内存大小,不同系统计算方式不同
- *free: 空闲未被分配的内存,Linux下不包括buffers和cached
Platform-specific fields:
- active: (UNIX): 最近使用内存和正在使用内存。
- inactive: (UNIX): 已经分配但是没有使用的内存
- buffers: (Linux, BSD): 缓存,linux下的Buffers
- cached:(Linux, BSD): 缓存,Linux下的cached.
- wired: (BSD, OSX): 一直存在于内存中的部分,不会被移除
- shared: (BSD): 缓存
内存总大小不等于Used+available,在windows系统可用内存和空闲内存是用一个。
|
|
返回系统的swap信息
- total: swap的总大小 单位为字节
- used: 已用的swap大小 bytes
- free: 空闲的swap大小 bytes
- percent: 已用swap的百分比
- sin: 从磁盘调入是swap的大小
- sout: 从swap调出到disk的大小
sin
,sout
在windows没有意义。
分区
|
|
返回所有挂载的分区的信息的列表,列表中的每一项类似于df命令的格式输出,包括分区,挂载点,文件系统格式,挂载参数等,会忽略掉/dev/shm
,/proc/filesystem
等,windows上分区格式 “removable
“, “fixed
“, “remote
“, “cdrom
“, “unmounted
“ or “ramdisk
“。
|
|
|
|
返回硬盘,分区或者目录的使用情况,单位字节
如果不存在会报“OSError
”错误。
|
|
|
|
返回当前磁盘的io情况
- read_count: number of reads
- write_count: number of writes
- read_bytes: number of bytes read
- write_bytes: number of bytes written
- read_time: time spent reading from disk (in milliseconds)
- write_time: time spent writing to disk (in milliseconds)
网络信息
返回整个系统的网络信息
|
|
- bytes_sent: 发送的字节数
- bytes_recv: 接收的字节数
- packets_sent: 发送到数据包的个数
- packets_recv: 接受的数据包的个数
- errin:
- errout: 发送数据包错误的总数
- dropin: 接收时丢弃的数据包的总数
- dropout: 发送时丢弃的数据包的总数(OSX和BSD系统总是0)
如果 pernic
值为True,会显示具体各个网卡的信息。
|
|
|
|
返回系统的整个socket连接的信息,可以选择查看哪些类型的连接信息,类似于netstat命令
fd:
family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
type: the address type, either SOCK_STREAM or SOCK_DGRAM.
laddr: the local address as a (ip, port) tuple or a path in case of AF_UNIX sockets.
raddr: the remote address as a (ip, port) tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or None (AF_UNIX). On Linux AF_UNIX sockets will always have this set to None. status: represents the status of a TCP connection. The return value is one of the psutil.CONN_* constants (a string). For UDP and UNIX sockets this is always going to be psutil.CONN_NONE.
pid: the PID of the process which opened the socket, if retrievable, else None. On some platforms (e.g. Linux) the availability of this field **changes depending on process privileges (root is needed).
参数kind的类型:
“inet” IPv4 and IPv6
“inet4” IPv4
“inet6” IPv6
“tcp” TCP
“tcp4” TCP over IPv4
“tcp6” TCP over IPv6
“udp” UDP
“udp4” UDP over IPv4
“udp6” UDP over IPv6
“unix” UNIX socket (both UDP and TCP protocols)
“all” the sum of all the possible families and protocols
>>>
>>> import psutil
>>> psutil.net_connections()
[pconn(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED', pid=1254),
pconn(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING', pid=2987),
pconn(fd=-1, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED', pid=None),
pconn(fd=-1, family=2, type=1, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT', pid=None)
...]`
|
|
`>>>
>>> import psutil
>>> psutil.users()
[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]`
|
|
`>>>
>>> import psutil, datetime
>>> psutil.boot_time()
1389563460.0
>>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
'2014-01-12 22:51:00'`
|
|
`import psutil
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
except psutil.NoSuchProcess:
pass
else:
print(pinfo)`
|
|
`import psutil
def on_terminate(proc):
print("process {} terminated".format(proc))
procs = [...] # a list of Process instances
for p in procs:
p.terminate()
gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
for p in alive:
p.kill()`
|
|
`>>>
>>> import psutil, datetime
>>> p = psutil.Process()
>>> p.create_time()
1307289803.47
>>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S")
'2011-03-05 18:03:52'`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.as_dict(attrs=['pid', 'name', 'username'])
{'username': 'giampaolo', 'pid': 12366, 'name': 'python'}`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.nice(10) # set
>>> p.nice() # get
10
>>>`
|
|
`>>>
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # set
>>> p.ionice() # get
pionice(ioclass=3, value=0)
>>>`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> # process may open no more than 128 file descriptors
>>> p.rlimit(psutil.RLIMIT_NOFILE, (128, 128))
>>> # process may create files no bigger than 1024 bytes
>>> p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024))
>>> # get
>>> p.rlimit(psutil.RLIMIT_FSIZE)
(1024, 1024)
>>>`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.io_counters()
pio(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0)`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>>
>>> # blocking
>>> p.cpu_percent(interval=1)
2.0
>>> # non-blocking (percentage since last call)
>>> p.cpu_percent(interval=None)
2.9
>>>`
|
|
`>>>
>>> import psutil
>>> psutil.cpu_count()
4
>>> p = psutil.Process()
>>> p.cpu_affinity() # get
[0, 1, 2, 3]
>>> p.cpu_affinity([0]) # set; from now on, process will run on CPU #0 only
>>> p.cpu_affinity()
[0]
>>>
>>> # reset affinity against all CPUs
>>> all_cpus = list(range(psutil.cpu_count()))
>>> p.cpu_affinity(all_cpus)
>>>`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.memory_info_ex()
pextmem(rss=15491072, vms=84025344, shared=5206016, text=2555904, lib=0, data=9891840, dirty=0)`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process()
>>> p.memory_maps()
[pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
pmmap_grouped(path='/lib/x8664-linux-gnu/libcrypto.so.0.1', rss=34124, anonymous=1245, swap=0),
pmmap_grouped(path='[heap]', rss=54653, anonymous=8192, swap=0),
pmmap_grouped(path='[stack]', rss=1542, anonymous=166, swap=0),
...]
>>>`
|
|
`>>> p.children()
B, C, D
>>> p.children(recursive=True)
B, X, Y, C, D`
|
|
`>>>
>>> import psutil
>>> f = open('file.ext', 'w')
>>> p = psutil.Process()
>>> p.open_files()
[popenfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3)]`
|
|
`>>>
>>> import psutil
>>> p = psutil.Process(1694)
>>> p.name()
'firefox'
>>> p.connections()
[pconn(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED'),
pconn(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING'),
pconn(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED'),
pconn(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT')]`
|
|
`>>>
>>> import psutil
>>> from subprocess import PIPE
>>>
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
>>> p.name()
'python'
>>> p.username()
'giampaolo'
>>> p.communicate()
('hello\n', None)
>>> p.wait(timeout=2)
0
>>>
Constants
psutil.STATUS_RUNNING
psutil.STATUS_SLEEPING
psutil.STATUS_DISK_SLEEP
psutil.STATUS_STOPPED
psutil.STATUS_TRACING_STOP
psutil.STATUS_ZOMBIE
psutil.STATUS_DEAD
psutil.STATUS_WAKE_KILL
psutil.STATUS_WAKING
psutil.STATUS_IDLE
psutil.STATUS_LOCKED
psutil.STATUS_WAITING
A set of strings representing the status of a process. Returned by psutil.Process.status().
psutil.CONN_ESTABLISHED
psutil.CONN_SYN_SENT
psutil.CONN_SYN_RECV
psutil.CONN_FIN_WAIT1
psutil.CONN_FIN_WAIT2
psutil.CONN_TIME_WAIT
psutil.CONN_CLOSE
psutil.CONN_CLOSE_WAIT
psutil.CONN_LAST_ACK
psutil.CONN_LISTEN
psutil.CONN_CLOSING
psutil.CONN_NONE
psutil.CONN_DELETE_TCB(Windows)
psutil.CONN_IDLE(Solaris)
psutil.CONN_BOUND(Solaris)
A set of strings representing the status of a TCP connection. Returned by psutil.Process.connections() (status field).
psutil.ABOVE_NORMAL_PRIORITY_CLASS
psutil.BELOW_NORMAL_PRIORITY_CLASS
psutil.HIGH_PRIORITY_CLASS
psutil.IDLE_PRIORITY_CLASS
psutil.NORMAL_PRIORITY_CLASS
psutil.REALTIME_PRIORITY_CLASS
A set of integers representing the priority of a process on Windows (see MSDN documentation). They can be used in conjunction with psutil.Process.nice() to get or set process priority.
Availability: Windows
psutil.IOPRIO_CLASS_NONE
psutil.IOPRIO_CLASS_RT
psutil.IOPRIO_CLASS_BE
psutil.IOPRIO_CLASS_IDLE
A set of integers representing the I/O priority of a process on Linux. They can be used in conjunction with psutil.Process.ionice() to get or set process I/O priority. IOPRIO_CLASS_NONE and IOPRIO_CLASS_BE (best effort) is the default for any process that hasn’t set a specific I/O priority. IOPRIO_CLASS_RT (real time) means the process is given first access to the disk, regardless of what else is going on in the system. IOPRIO_CLASS_IDLE means the process will get I/O time when no-one else needs the disk. For further information refer to manuals of ionice command line utility or ioprio_get system call.
Availability: Linux
psutil.RLIMIT_INFINITY
psutil.RLIMIT_AS
psutil.RLIMIT_CORE
psutil.RLIMIT_CPU
psutil.RLIMIT_DATA
psutil.RLIMIT_FSIZE
psutil.RLIMIT_LOCKS
psutil.RLIMIT_MEMLOCK
psutil.RLIMIT_MSGQUEUE
psutil.RLIMIT_NICE
psutil.RLIMIT_NOFILE
psutil.RLIMIT_NPROC
psutil.RLIMIT_RSS
psutil.RLIMIT_RTPRIO
psutil.RLIMIT_RTTIME
psutil.RLIMIT_RTPRIO
psutil.RLIMIT_SIGPENDING
psutil.RLIMIT_STACK
Constants used for getting and setting process resource limits to be used in conjunction with psutil.Process.rlimit(). See man prlimit for futher information.
Availability: Linux