python模块之psutil详解
一、psutil模块:
1.psutil是一个跨平台库(http://pythonhosted.org/psutil/)能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要用来做系统监控,性能分析,进程管理。它实现了同等命令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等。目前支持32位和64位的Linux、Windows、OS X、FreeBSD和Sun Solaris等操作系统.
2.安装psutil模块:
CentOS安装psutil包:
python版本:3.5 wget https://pypi.python.org/packages/source/p/psutil/psutil-3.2.1.tar.gz --no-check-certificate
tar zxvf psutil-3.2.1.tar.gz
cd psutil-3.2.1
python setup.py install Windos安装psutil包: D:\python35\Scripts>pip3.exe install psutil
Collecting psutil
Downloading psutil-5.3.1-cp35-cp35m-win_amd64.whl (215kB)
100% |████████████████████████████████| 225kB 84kB/s
Installing collected packages: psutil
Successfully installed psutil-5.3.1
二、.获取系统基本信息的使用:
1.CPU信息
使用cpu_times方法获取cpu的完整信息,如下所示。
>>> psutil.cpu_times()
scputimes(user=650613.02, nice=22.14, system=154916.5, idle=16702285.26, iowait=68894.55, irq=3.38, softirq=7075.65, steal=0.0, guest=0.0)
>>>
获取单个数据,如用户的cpu时或io等待时间,如下所示:
>>> psutil.cpu_times().user
650617.11
>>> psutil.cpu_times().iowait
68894.63
>>>
获取cpu逻辑和物理个数,默认logical值为True 。
#CPU逻辑个数
>>> psutil.cpu_count() #CPU物理个数
>>> psutil.cpu_count(logical=False) >>>
获取cpu的使用率:
>>> psutil.cpu_percent()
2.5
>>> psutil.cpu_percent()
2.5
>>>
2.内存信息
内存信息的获取主要使用virtual_memory方法。swap使用就用swap_memory方法。
>>> mem = psutil.virtual_memory()
>>> mem
svmem(total=, available=, percent=73.5, used=, free=, active=, inactive=, buffers=, cached=)
>>> mem.total >>> mem.used >>> mem.free >>> print(mem.total//)
3832.4375
>>>
其中percent表示实际已经使用的内存占比,即(1047543808-717537280)/1047543808*100% 。available表示还可以使用的内存。
3.磁盘信息
磁盘信息主要有两部分,一个是磁盘的利用率,一个是io,他们分别可以通过disk_usage和disk_io_counters方法获取。
如下先获取分区信息,然后看下根分区的使用情况:
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/mapper/root', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='ext2', opts='rw')]
>>> psutil.disk_usage('/')
sdiskusage(total=, used=, free=, percent=40.8)
>>>
默认disk_io_counters方法获取的是硬盘总的io数和读写信息,如果需要获取单个分区的io和读写信息加上"perdisk=True"参数。
>>> psutil.disk_io_counters()
sdiskio(read_count=, write_count=, read_bytes=, write_bytes=, read_time=, write_time=)
>>> psutil.disk_io_counters(perdisk=True)
{'vdb1': sdiskio(read_count=, write_count=, read_bytes=, write_bytes=, read_time=, write_time=), 'vda1': sdiskio(read_count=, write_count=, read_bytes=, write_bytes=, read_time=, write_time=)}
>>>
4.网络信息:
网络io和磁盘io使用方法差不多,主要使用net_io_counters方法,如果需要获取单个网卡的io信息,加上pernic=True参数。
#获取网络总的io情况
>>>
>>> psutil.net_io_counters()
snetio(bytes_sent=, bytes_recv=, packets_sent=, packets_recv=, errin=, errout=, dropin=, dropout=)
#获取网卡的io情况
>>>
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=, bytes_recv=, packets_sent=, packets_recv=, errin=, errout=, dropin=, dropout=), 'eth0': snetio(bytes_sent=, bytes_recv=, packets_sent=, packets_recv=, errin=, errout=, dropin=, dropout=)}
>>>
5.其他系统信息:
1.获取开机时间
##以linux时间格式返回,可以使用时间戳转换
>>> psutil.boot_time()
1496647567.0 #转换成自然时间格式
>>> psutil.boot_time()
1496647567.0
>>> datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S")
'2017-06-05 15: 26: 07'
>>>
2.查看系统全部进程
>>> psutil.pids()
[, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
3.查看单个进程
p = psutil.Process(16031)
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()
查看系统硬件脚本:
#!/usr/bin/env python
#coding:utf-8 import psutil
import datetime
import time # 当前时间
now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
print(now_time) # 查看cpu物理个数的信息
print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False)) #CPU的使用率
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cup使用率: %s" % cpu) #查看内存信息,剩余内存.free 总共.total
#round()函数方法为返回浮点数x的四舍五入值。 free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
print(u"物理内存: %s G" % total)
print(u"剩余物理内存: %s G" % free)
print(u"物理内存使用率: %s %%" % int(memory * 100))
# 系统启动时间
print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")) # 系统用户
users_count = len(psutil.users())
#
# >>> for u in psutil.users():
# ... print(u)
# ...
# suser(name='root', terminal='pts/0', host='61.135.18.162', started=1505483904.0)
# suser(name='root', terminal='pts/5', host='61.135.18.162', started=1505469056.0)
# >>> u.name
# 'root'
# >>> u.terminal
# 'pts/5'
# >>> u.host
# '61.135.18.162'
# >>> u.started
# 1505469056.0
# >>> users_list = ",".join([u.name for u in psutil.users()])
print(u"当前有%s个用户,分别是 %s" % (users_count, users_list)) #网卡,可以得到网卡属性,连接数,当前流量等信息
net = psutil.net_io_counters()
bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
print(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent)) io = psutil.disk_partitions()
# print(io)
# print("io[-1]为",io[-1])
#del io[-1] print('-----------------------------磁盘信息---------------------------------------') print("系统磁盘信息:" + str(io)) for i in io:
o = psutil.disk_usage(i.device)
print("总容量:" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G") print('-----------------------------进程信息-------------------------------------')
# 查看系统全部进程
for pnum in psutil.pids():
p = psutil.Process(pnum)
print(u"进程名 %-20s 内存利用率 %-18s 进程状态 %-10s 创建时间 %-10s " \
% (p.name(), p.memory_percent(), p.status(), p.create_time()))
硬件信息脚本
以上是psutil模块获取linux系统基础信息的几个方法,大概常用的数据就这些。当然其他用法还有很多,详情可以参考他的官方文档。
网址:http://pythonhosted.org/psutil/
http://www.cnblogs.com/liu-yao/p/5678157.html
http://www.sijitao.net/2043.html
http://www.cnblogs.com/luomingchuan/p/3777269.html
http://www.sijitao.net/2016.html
python模块之psutil详解的更多相关文章
- Python模块调用方式详解
Python模块调用方式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其 ...
- python模块之XlsxWriter 详解
Xlsx是python用来构造xlsx文件的模块,可以向excel2007+中写text,numbers,formulas 公式以及hyperlinks超链接. 可以完成xlsx文件的自动化构造,包括 ...
- python模块与包详解
<1>.模块:任何 *.py 的文件都可以当作模块使用 import 导入 >>>improt test >>>b=test.a() >> ...
- python模块的导入详解
一:一个小问题:什么是模块? 我的理解是:有通用功能的文件的集合. 二:为什么要使用模块? 我们通常为了使自己以前写的东西保存下来,会把东西写入文件中保存下来,必要时我们把这些文件当脚本去执行,也可以 ...
- python中argparse模块用法实例详解
python中argparse模块用法实例详解 这篇文章主要介绍了python中argparse模块用法,以实例形式较为详细的分析了argparse模块解析命令行参数的使用技巧,需要的朋友可以参考下 ...
- Python中random模块生成随机数详解
Python中random模块生成随机数详解 本文给大家汇总了一下在Python中random模块中最常用的生成随机数的方法,有需要的小伙伴可以参考下 Python中的random模块用于生成随机数. ...
- Nginx RTMP 模块 nginx-rtmp-module 指令详解
译序:截至 Jul 8th,2013 官方公布的最新 Nginx RTMP 模块 nginx-rtmp-module 指令详解.指令Corertmp语法:rtmp { ... }上下文:根描述:保存所 ...
- Python对Excel操作详解
Python对Excel操作详解 文档摘要: 本文档主要介绍如何通过python对office excel进行读写操作,使用了xlrd.xlwt和xlutils模块.另外还演示了如何通过Tcl ...
- Python初学者常见错误详解
Python初学者常见错误详解 0.忘记写冒号 在 if.elif.else.for.while.class.def 语句后面忘记添加 “:” if spam == 42 print('Hello ...
随机推荐
- Logistic回归分析简介
Logistic回归:实际上属于判别分析,因拥有很差的判别效率而不常用. 1. 应用范围: ① 适用于流行病学资料的危险因素分析 ② 实验室中药物的剂量-反应关系 ③ 临床试验 ...
- 如何生动形象、切中要点地讲解 OSI 七层模型和两主机传输过程
作者:繁星亮与鲍包包链接:https://www.zhihu.com/question/24002080/answer/31817536来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转 ...
- java 获取 path
(1).request.getRealPath("/");//不推荐使用获取工程的根路径 (2).request.getRealPath(request.getRequestURI ...
- iOS 使用Masonry介绍与使用实践:快速上手Autolayout
介绍 Masonry 源码:https://github.com/Masonry/Masonry Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 ...
- Spring security 用户,角色,权限,资源
转自:http://blog.csdn.net/wybqq/article/details/52940194 关于Spring security对用户请求的处理过程 体现在这两个过程的体现. 关于用户 ...
- 编写js语句结束时保持良好的习惯-源于身边例子
记录以下信息,源于一件事情,一位同事,每次我改他的js代码,发现语句结束都不使用分号作为结束.长长的一串,读起来比较吃力.即便语句的结束不使用分号结束,代码仍然不会报错,正常运行,所以不少程序员懒得去 ...
- Linux 下编译出现 undefined reference to `pthread_create'
这是由于没有链接线程库的原因,只要在编译的时候加入: -lpthread 参数即可. arm-linux-gcc serial.c -o serial -lpthread 查看 ubuntu 版本的命 ...
- [dig]使用dig查看当前网络连通情况
1. dig domain, 通过server可以查到该域名被哪个server给解析了 2. dig @dns domain 不走/etc/resolve.conf,直接走指定的dns ------- ...
- STM32 双ADC同步规则采样
最近需要用到两个ADC对电压电流进行同步采样,看了一下STM32的ADC介绍,发现STM32最多有3个独立ADC,有在双AD模式下可以进行同步测量,正好满足我的要求.参考官方给的例子在结合自己的需 ...
- Windows API 常用函数
.Net中虽然类库很强的,但还是有些时候功能有限,掌握常用的api函数,会给我们解决问题提供另一种思路,下面给出自己常用到的Api函数,以备查询. 知道api函数,但却不知道c#或VB.net该如何声 ...