文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
使用 Psutil
Psutil 是一个跨平台的进程处理和系统工具模块,它可以获取系统 CPU、内存、硬盘和网络等信息,常用于系统资源的采集、监控、分析,以及进程管理。使用它可以用 Python 实现系统相关的命令行功能,比如 top、netstat、ps、iostat、ifconfig、df,具体实现可以参考项目代码下的 scripts 目录(http://bit.ly/28SOjEX )。目前使用它的应用有 Psdash、Glances 等。虽然它主要应用于运维开发中,但是在应用代码中也可以使用它增加一些这方面的功能。举两个例子:
- 启动定时任务时需要确保之前的定时任务都已完成,否则要直接退出或者杀掉这些之前没有完成的进程,再开始。
- 当应用在内存占用等方面有问题时,加入 Psutil 代码,监控对应内存(或其他指标)的使用情况来帮助确定原因。
我们先安装它:
> pip install psutil
常用的函数有如下 10 个。
1.cpu_percent:返回当前 CPU 的利用率的百分比。
In:psutil.cpu_percent() #它接受两个参数:interval 是统计的间隔,percpu 为 True 会返回所有逻辑 CPU 的利用率的列表 Out:32.6
2.cpu_count:获得逻辑(物理)CPU 的个数。
In:psutil.cpu_count() Out:24 In:psutil.cpu_count(logical=False) #获取物理 CPU 数,会去掉超线程 CPU 的数量 Out:2 #数据差别很大
3.virtual_memory:内存占用情况。
In [2]:psutil.virtual_memory()
Out[2]:svmem(total=101540593664L, available=77059371008L, percent=24.1, used
=89900863488L, free=11639730176L, active=25916870656, inactive=57613012992,
buffers=6373376L, cached=65413267456)
其中:
- total 表示全部内存。
- available 表示可以用来分配的内存。不同系统的计算方式不同,在 Linux 下是 free+buffers+cached。
- percent 表示使用的内存的占比,也就是(total-available)/total*100。
- used 表示已经用到的内存。不同系统的计算方式不同。
- free 表示未被分配的内存。Linux 下不包括 buffers 和 cached。
4.disk_partitions:硬盘分区信息,返回所有挂载的分区的信息的列表。列表中的每一项类似于 df 命令的格式输出,包括分区、挂载点、文件系统格式、挂载参数等。
In:psutil.disk_partitions()
Out:
[sdiskpart(device='/dev/root', mountpoint='/', fstype='xfs', opts='rw,noatime,
nodiratime,attr2,delaylog,nobarrier,noquota'),
sdiskpart(device='/dev/sda2', mountpoint='/data1', fstype='xfs', opts='rw,
noatime,nodiratime,nobarrier')]
5.disk_usage:返回硬盘,分区或者目录的使用情况,单位为字节。
In : psutil.disk_usage('/')
Ou : sdiskusage(total=42928640000, used=40646586368, free=2282053632, percent
=94.7)
6.pids:获得当前运行的程序进程的 id 列表。
In : pids=psutil.pids()
7.pid_exists:检查程序 id 是否存在,可以理解为“pid in psutil.pids()”的快捷方式。
In:psutil.pid_exists(11111) Out:False In:psutil.pid_exists(pids[10]) Out:True
8.Process:操作进程的类。
In : p=psutil.Process(pid=pids[100])
In : datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d%H:%M:%S")
Out: '2016-03-06 06:17:04'
In : p.as_dict(attrs=['pid', 'name', 'username'])
Out: {'name':'tail', 'pid':1414, 'username':'dongwm'}
In : p.cpu_percent(interval=1)
Out: 1.0
In : p.memory_info()
pmem(rss=15491072, vms=84025344, shared=5206016, text=2555904, lib=0, data
=9891840, dirty=0)
In : p2=psutil.Process() #获取当前进程实例 In:p2
Out: <psutil.Process(pid=341, name='ipython') at 37342416>In:p2.cpu_affinity([5]) #把进程绑到第 6 个 CPU 上
In : p2.open_files()
Out:
[popenfile(path='/home/ubuntu/.ipython/profile_default/history.sqlite', fd=3),
popenfile(path='/home/ubuntu/.ipython/profile_default/history.sqlite', fd=4)]
In : p2.cmdline()
Out: ['/usr/bin/python2.7', '/home/ubuntu/web_develop/venv/bin/ipython']
In : p2.kill() #杀掉了自己
[1] 341 killed /home/ubuntu/web_develop/venv/bin/ipython
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论