psutil 是一个python 的跨平台的库,可以用来获取进程和系统运行状态(CPU、内存、磁盘,网络、传感器)
它对于系统和进程的监控、分析以及资源管理非常有用。
它实现了unix下面的很多命令,例如:ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice
ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等
psutil支持平台:
linux、windows、osx、freebsd、openbsd、netbsd、sun solaris aix
Python版本从2.6到3.6(Python 2.4和2.5的用户可能使用2.1.3版本)的32位和64位体系结构。
安装 pip install psutil
linux tar包安装
先安装gcc、python-dev包
系统相关功能
#-*-encoding:utf-8-*- import psutil import time CPU: psutil.cpu_times(percpu=False) 返回一个命名元组系统cpu运行时间。每个属性表示CPU在给定模式下花费的秒数。 属性取决于运行的平台 True 返回每个核的信息 print(psutil.cpu_times(percpu=False)) 输出:scputimes(user=17411.7, nice=77.99, system=3797.02, idle=51266.57, iowait=732.58, irq=0.01, softirq=142.43, steal=0.0, guest=0.0, guest_nice=0.0) psutil.cpu_percent(interval=None, percpu=False) 返回cpu使用率 interval大于0时,返回internal间隔内cpu使用率,internal等于0或者None时, 返回距离上次调用或者导入psutil时到目前cpu使用率 time.sleep(1) print(psutil.cpu_percent(interval=None, percpu=True)) 输出[6.2, 4.7, 21.9, 0.0] psutil.cpu_times_percent(interval=None, percpu=False) 同cpu_percent,但是提供cpu具体使用百分比 time.sleep(1) print(psutil.cpu_times_percent(interval=None, percpu=False)) 输出scputimes(user=7.8, system=7.0, idle=85.2, interrupt=0.0, dpc=0.0) psutil.cpu_count(logical=False) 返回cpu核数,默认True,False返回物理核数 print(psutil.cpu_count(logical=False)) psutil.cpu_stats() 返回cpu统计信息,上下文切换次数、中断次数、软中断次数、系统调用次数 print(psutil.cpu_stats()) 输出scpustats(ctx_switches=1496277294, interrupts=726380236, soft_interrupts=0, syscalls=586390840) psutil.cpu_freq(percpu=False) 返回cpu频率 print(psutil.cpu_freq(percpu=False)) 输出scpufreq(current=3300.0, min=0.0, max=3300.0) Memory psutil.virtual_memory() 返回系统内存统计信息 print(psutil.virtual_memory()) 输出(linux)svmem(total=4157956096, available=3496386560, percent=15.9, used=468250624, free=3009159168, active=755118080, inactive=279117824, buffers=41791488, cached=638754816, shared=438272, slab=58466304) 内存总数、可用数、使用百分比、使用数、空闲数、正在使用或者最近使用数、未使用数、缓存数、混存数、共享内存、内核数据缓存 注available的解释:the memory that can be given instantly to processes without the system going into swap. This is calculated by summing different memory values depending on the platform and it is supposed to be used to monitor actual memory usage in a cross platform fashion. """关于linux中的free -m解释 在命令行执行free -m 出现如下的一些相关信息(计量单位(M)),当然每台机器的内存不一样,会有所差异 total used free shared buffers cached Mem: 1002 769 232 0 62 421 -/+ buffers/cache: 286 715 Swap: 1153 0 1153 第一行Mem total表示是当前内存的总数:1024 used表示当前已经使用内存数:769 free 表示当前可用的内存数:232 shared 目前这个基本为0 不常用 buffers 缓存内存数:62 cached 混村内存数:421 他们之间的关系:total=used+free(总数=使用数+剩余) 第二行-/+ buffers/cache -buffers/cache used内存数:used=286(Mem中的 used-buffers-cached) +buffers/cache free内存数: free=715(Mem中的 free+buffers+cached) 从这里我们可以看出来-buffers-cached是被程序实实在在使用的内存,而+buffers/cache反应的则是可以挪用的内存数""" psutil.swap_memory() 返回系统交换区内存信息统计 print(psutil.swap_memory()) sswap(total=16527077376, used=7392493568, free=9134583808, percent=44.7, sin=0, sout=0) 总数、使用数、空闲数、百分比、系统从磁盘交换的字节数、系统从磁盘中换出的字节数 Disks psutil.disk_partitions(all=True) 返回所有挂载分区信息 print(psutil.disk_partitions(all=True)) 输出[sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='E:\\', mountpoint='E:\\', fstype='NTFS', opts='rw,fixed')] psutil.disk_usage(path) 返回目录使用空间信息 print(psutil.disk_usage('/')) sdiskusage(total=20091629568, used=2059567104, free=17004617728, percent=10.8) psutil.disk_io_counters(perdisk=False, nowrap=True) 返回系统i/o统计信息 print(psutil.disk_io_counters(perdisk=False, nowrap=True)) sdiskio(read_count=25977, write_count=186427, read_bytes=306666496, write_bytes=2605129728, read_time=248720, write_time=15947848, read_merged_count=369, write_merged_count=449606, busy_time=3296568) Network psutil.net_io_counters(pernic=False, nowrap=True) print(psutil.net_connections()) print(psutil.net_io_counters(pernic=True, nowrap=True)) {'lo': snetio(bytes_sent=87484572, bytes_recv=87484572, packets_sent=1123987, packets_recv=1123987, errin=0, errout=0, dropin=0, dropout=0), 'wafbridge1': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0), 'eth5': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0), 'eth4': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0), 'eth3': snetio(bytes_sent=4947628, bytes_recv=1088573281, packets_sent=26751, packets_recv=9489744, errin=0, errout=0, dropin=2, dropout=0), 'eth2': snetio(bytes_sent=77085278, bytes_recv=1201803903, packets_sent=97206, packets_recv=9601081, errin=0, errout=0, dropin=34483, dropout=0), 'eth1': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)} psutil.net_connections(kind='inet') print(psutil.net_connections(kind='inet')) fd 文件描述符 family AF_INET、AF_INET6 or AF_UNIX type (SOCK_STREAM/SOCK_DGRAM) laddr 本地ip和端口 raddr 远端ip和端口 status 连接状态 pid 进程号 Kind value Connections using "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 psutil.net_if_addrs() 返回网卡信息 print(psutil.net_if_addrs()) {'eth3': [snic(family=2, address='192.168.100.1', netmask='255.255.255.0', broadcast='192.168.100.255', ptp=None), snic(family=10, address='fe80::20c:29ff:fe88:89a7%eth3', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snic(family=17, address='00:0c:29:88:89:a7', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)], 'lo': [snic(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snic(family=10, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snic(family=17, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)], 'eth5': [snic(family=17, address='00:0c:29:88:89:c5', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)], 'eth4': [snic(family=2, address='192.168.1.11', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None), snic(family=17, address='00:0c:29:88:89:bb', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)], 'wafbridge1': [snic(family=17, address='00:0c:29:88:89:cf', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)], 'eth2': [snic(family=2, address='192.168.99.60', netmask='255.255.255.0', broadcast='192.168.99.255', ptp=None), snic(family=10, address='fe80::20c:29ff:fe88:89b1%eth2', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snic(family=17, address='00:0c:29:88:89:b1', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)], 'eth1': [snic(family=17, address='00:0c:29:88:89:d9', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)], 'eth0': [snic(family=17, address='00:0c:29:88:89:cf', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]} psutil.net_if_stats() 返回网卡信息 print(psutil.net_if_stats()) {'eth3': snicstats(isup=True, duplex=2, speed=1000, mtu=1500), 'lo': snicstats(isup=True, duplex=0, speed=0, mtu=65536), 'eth5': snicstats(isup=False, duplex=0, speed=65535, mtu=1500), 'eth4': snicstats(isup=True, duplex=0, speed=65535, mtu=1500), 'wafbridge1': snicstats(isup=True, duplex=0, speed=0, mtu=1500), 'eth2': snicstats(isup=True, duplex=2, speed=1000, mtu=1500), 'eth1': snicstats(isup=True, duplex=0, speed=65535, mtu=1500), 'eth0': snicstats(isup=True, duplex=0, speed=65535, mtu=1500)} Sensors psutil.sensors_temperatures(fahrenheit=False) 返回硬件温度 print(psutil.sensors_temperatures(fahrenheit=False)) {'coretemp': [shwtemp(label='Physical id 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 1', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 2', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 3', current=100.0, high=100.0, critical=100.0)]} psutil.sensors_fans() 返回风扇速度 print(psutil.sensors_fans()) psutil.sensors_battery() 返回电池使用情况 Other system info 系统启动时间 print(psutil.boot_time()) 返回连接到系统的用户 print(psutil.users()) [suser(name='Administrator', terminal=None, host='0.0.0.0', started=1526539294.0, pid=None)] Processes psutil.pids() print(psutil.pids()) 返回系统运行进程的id psutil.process_iter(attrs=None, ad_value=None) 返回一个迭代器,包含每个进程的信息 for proc in psutil.process_iter(attrs=None, ad_value=None): print(proc) psutil.Process(pid=0, name='System Idle Process', started='2018-05-16 08:10:18') psutil.Process(pid=4, name='System', started='2018-05-16 08:10:18') psutil.Process(pid=120, name='vmware-remotemks.exe', started='09:40:27') psutil.Process(pid=280, name='smss.exe', started='2018-05-16 08:10:30') for proc in psutil.process_iter(attrs=['pid', 'name', 'username']): print(proc.info) {'name': 'audiodg.exe', 'username': None, 'pid': 11840} {'name': 'WmiPrvSE.exe', 'username': None, 'pid': 11932} {'name': 'wpscenter.exe', 'username': 'USER-20150701JV\\Administrator', 'pid': 12732} {'name': 'aliwssv.exe', 'username': 'USER-20150701JV\\Administrator', 'pid': 14160} {'name': 'conhost.exe', 'username': 'USER-20150701JV\\Administrator', 'pid': 14168} psutil.pid_exists(pid) print(psutil.pid_exists(0)) 返回是否包含pid的进程 def on_terminate(proc): print("process {} terminated with exit code {}".format(proc, proc.returncode)) procs = psutil.Process().children() for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate) for p in alive: p.kill() Exceptions psutil异常 psutil.Error psutil.NoSuchProcess(pid, name=None, msg=None) psutil.AccessDenied(pid=None, name=None, msg=None) psutil.TimeoutExpired(seconds, pid=None, name=None, msg=None) Process class psutil.Process(pid=None) 默认当前进程 Linux : cpu_num() cpu_percent() cpu_affinity(cpus=None) cpu亲和性 cpu_times() create_time() 创建时间 name() 进程名称 ppid() 父进程pid status() 状态 terminal() 与终端相关信息 gids() 组id num_ctx_switches() 上下文切换累计次数 num_threads() uids() 用户id username() memory_full_info() memory_maps() exe() 执行绝对路径 cmdline() 字符串列表 environ() 环境变量 as_dict(attrs=None, ad_value=None) attrs 为列表可以包含所有方法名称调用后返回对应信息 p = psutil.Process() print(p.as_dict(attrs=['pid', 'name', 'memory_maps'])) cwd() 当前工作路径 nice() 获取或设置优先级 p = psutil.Process() p.nice(10) # set p.nice() # get ionice() 获取或设置i/o优先级 p = psutil.Process() p.ionice(psutil.IOPRIO_CLASS_IDLE) # set p.ionice() # get io_counter() 获取i/o统计信息 print(psutil.Process().io_counters()) pio(read_count=120, write_count=0, read_bytes=922004, write_bytes=0, other_count=2440, other_bytes=140478) num_fds() 此进程打开的文件描述符 num_handles() 进程使用的句柄 num_threads() 进程包含的线程数 threads() 进程包含的线程的信息 print(psutil.Process().memory_info()) print(psutil.Process().memory_info_ex()) print(psutil.Process().memory_full_info()) print(psutil.Process().memory_percent(memtype="rss")) print(psutil.Process().memory_maps(grouped=True))
上面内容只是简单介绍psutil模块,其中返回值具体含义可以自行百度
参考链接:http://psutil.readthedocs.io/en/latest/#psutil.Process.rlimit