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 timeCPU:
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)
总数、使用数、空闲数、百分比、系统从磁盘交换的字节数、系统从磁盘中换出的字节数

Diskspsutil.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 protocolspsutil.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)}

Sensorspsutil.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)]

Processespsutil.pids()
print(psutil.pids())
返回系统运行进程的idpsutil.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

python psutil 简介相关推荐

  1. 初识python psutil

    转自: https://pypi.python.org/pypi/psutil http://www.crifan.com/try_python_psutil/ http://www.open-ope ...

  2. 《从问题到程序:用Python学编程和计算》——1.2 Python语言简介

    本节书摘来自华章计算机<从问题到程序:用Python学编程和计算>一书中的第1章,第1.2节,作者 裘宗燕,更多章节内容可以访问云栖社区"华章计算机"公众号查看. 1. ...

  3. python psutil模块 硬盘厂家芯片型号_python第三方模块—psutil模块

    系统基础信息采集模块作为监控模块的重要组成部分,能够帮助运维人员了解当前系统的健康程度,同时也是衡量业务的服务质量的依据,比如系统资源吃紧,会直接影响业务的服务质量及用户体验,另外获取设备的流量信息, ...

  4. Python列表简介

    Python列表简介 什么是列表 #普通的变量定义形式 tom ='Tom' jack ='Jack' john ='John'pet1 ='cat' pet2 ='dog' pet3 ='bird' ...

  5. Python编程简介

    Python编程简介 2011年06月23日 NOTE: The following is a short tutorial about python program, for Chinese rea ...

  6. python psutil下载安装_windows 利用pip 安装python psutil 模块

    本来写好的一篇文章,点错了,点"发表文章"了,郁闷中.... https://www.cndba.cn/sule/article/2218 那么就简单的记录下吧,懒得再详细的写一遍 ...

  7. 大数据教程【05.01】--Python 数据分析简介

    更多信息请关注WX搜索GZH:XiaoBaiGPT Python数据分析简介 本教程将介绍如何使用Python进行大数据分析.Python是一种功能强大且易于使用的编程语言,具备丰富的数据分析库和工具 ...

  8. Python基础知识(Python的简介、Python环境的安装、集成开发环境Pycharm的安装)

    1.Python的简介 python是跨平台的计算机语言.解释型语言.交互式语言.面向对象语言.初学者最好学的语言 什么是跨平台:意思就是说可以在很多操作系统中执行.比如:可以在windows操作系统 ...

  9. Python Notebook简介

    windows下面安装和使用Python, IPython NoteBook (详细步骤) Python Notebook简介1 IPython notebook目前已经成为用Python做教学.计算 ...

最新文章

  1. 【Qt中文手册】QSortFilterProxyModel
  2. ubuntu16.0.4 opencv4.0.0 yolov3测试
  3. 机器学习导论(张志华):随机向量性质
  4. Stream流的常见生成方式
  5. Delphi中使用API将目录删除函数
  6. delphi mysql 图片_delphi数据库图片的存取 【转】
  7. [Java] 蓝桥杯BASIC-11 基础练习 十六进制转十进制
  8. 2017linux c校园招聘,华为2017校招C++岗笔试题
  9. Java 框架、库和软件的精选列表(Awesome Java)
  10. OpenVSwitch的端口Port学习使用
  11. jiathis jia.js Eval 解密 解密出来的代码
  12. CenterNet2:CenterNet再升级,原作者提出基于概率解释的两阶段目标检测
  13. CPU频率,到底是什么?
  14. 【Python】5行代码采集3000+上市公司信息
  15. STB 应用手册术语 2 - CA,EPG,VOD,CDN
  16. 百度地图API学习---隐藏百度版权标志
  17. 达内终端端mysql命令_如何从Windows命令行启动MySQL
  18. git flow 概念
  19. 在windows下如何配置RTT开发环境?
  20. getter方法的作用 vuex_vuex Getter

热门文章

  1. android条码支付开发,详解支付宝条码支付:1分钟完成收单 成本降低
  2. 国民体质测定标准计算机应用软件,(完整版)国民体质测定标准》(成年人部分.docx...
  3. 精耕细作——建行广东江门分行以数字化经营推进信用卡业务持续发展
  4. 《Ultra-High-Definition Television (Rec. ITU-R BT.2020): A Generational Leap in the Evoluti》,译名:超高清电视
  5. 6种有效的iOS团队开发技巧
  6. 利用MTALAB在坐标轴绘制三角形函数,或者绘制三角形
  7. 自学软件测试有没有好的书籍和配套课件?
  8. H5调用扫一扫(支持非微信环境)
  9. 极域电子教室-利用程序-轻松入侵全班同学电脑
  10. 阿里云集成短信验证码