《用python的话,一定要试着使用的函数》第六集。(psutil:python的系统监控)

《用python的话,一定要试着使用的函数》专栏的第六集。这集是关于python的系统监控。
这个专栏会确保短小精悍,学得快,看了不后悔。

用python的话,一定要试着使用的函数

第六集的主角是psutil。

这有什么用?

psutil(进程和系统实用程序)是一个跨平台库,用于 在 Python 中检索有关正在运行的进程和系统利用率(CPU、内存、磁盘、网络、传感器)的信息。它主要用于系统监视、分析和限制进程资源以及管理正在运行的进程。它实现了经典 UNIX 命令行工具提供的许多功能,例如ps、top、iotop、lsof、netstat、ifconfig、free等。psutil 目前支持以下平台:
1.Linux
2.Windows
3.macOS
4.FreeBSD, OpenBSD, NetBSD
5.Sun Solaris
6.AIX
(emmm,我只知道1,2,3,哈哈哈哈)

怎么装?

pip install psutil

怎么用?

获取CPU核心数和CPU线程数

import psutil
#获取CPU线程数
print(psutil.cpu_count())
#获取CPU核心数
print(psutil.cpu_count(logical=False))

结果是8和4
在这里插入图片描述
正好对应西瓜6的 4核mac。
在这里插入图片描述
如果你不懂CPU核心数和CPU线程数的意思。简单说一下就是。CPU核心数等于你电脑硬件上真的cpu数量,CPU线程数就是模拟出了多少cpu数量。(可以理解你公司里有4个人,但是你老板让这4个人干8个人的活)
更详细的可以看《CPU个数、CPU核心数、CPU线程数》:https://www.cnblogs.com/kimsimple/p/7787018.html

获取CPU信息(User、Nice、System、Idle)

import psutil

#获取cpu信息
print(psutil.cpu_times())

在这里插入图片描述
ⓐ User
User表示:CPU一共花了多少比例的时间运行在用户态空间或者说是用户进程(running user space processes)。典型的用户态空间程序有:Shells、数据库、web服务器……
ⓑ Nice
Nice表示:可理解为,用户空间进程的CPU的调度优先级,范围为[-20,19]
You can set the nice value when launching a process with the nice command and then change it with the renice command.
Only the superuser (root) can specify a priority increase of a process.
ⓒSystem
System的含义与User相似。System表示:CPU花了多少比例的时间在内核空间运行。分配内存、IO操作、创建子进程……都是内核操作。这也表明,当IO操作频繁时,System参数会很高。
When a user space process needs something from the system, for example when it needs to allocate memory, perform some I/O,
or it needs to create a child process, then the kernel is running
ⓓIdle
Idel表示:CPU处于空闲状态时间比例。一般而言,idel + user + nice 约等于100%
详细可以参考《关于CPU的User、Nice、System、Wait、Idle各个参数的解释》:https://www.cnblogs.com/hapjin/p/6296296.html

获取CPU总使用率和分别使用率

传说中的一核有难,多核捣乱

import psutil
#interval指定的是计算cpu使用率的时间间隔,percpu则指定是选择总的使用率还是每个cpu的使用率;
#获取cpu的总使用率
for x in range(3):
    print(psutil.cpu_percent(interval=1))

#获取cpu的分别使用率
for x in range(3):
    print(psutil.cpu_percent(interval=1, percpu=True))

在这里插入图片描述

注:稳妥起见interval设置的值要不小于0.1。
In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.

拓展一下

打住了,这个系列不能写太多。
还有很多功能如:获取内存信息,磁盘信息,网络信息,传感器信息,其他系统信息,进程管理(Process management),(更多进程APIs)Further process APIs,Popen wrapper,Windows服务(Windows services)
pypi文档:https://pypi.org/project/psutil/
github:https://github.com/giampaolo/psutil
《Python编程——psutil模块的使用详解》:https://blog.csdn.net/qq_38684504/article/details/87956015

结束语

嘿嘿,很好用的,有帮助就点个赞和关注咯。感谢各位。
西瓜6的啦啦啦

Guess you like

Origin blog.csdn.net/qq_37924224/article/details/117392984