[Python third-party library] Introduction to common methods of psutil module

1. Introduction to psutil

psutil:process and system utilities

psutil is a third-party module in python that needs to be downloaded. It can be easily achieved 获取系统运行的进程和系统利用率(CPU、内存、磁盘、网络等)信息,主要应用于系统监控.

Realized the functions realized by the same command line: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap, etc. 能够跨平台运行.

The main functions of psutil include: CPU, 磁盘, 内存, 网络, 进程and so on.
psutil can get a lot of low-level information, and it is a very useful tool when dealing with tasks such as system monitoring and resource management.

Two, psutil installation

pip install psutil

3. Common methods of psutil

import psutil
import datetime


def test():
#----------------CPU监控(linux命令:top)----------------
    # 获取 CPU 的逻辑数量:默认返回逻辑CPU的个数,当设置logical的参数为False时,返回物理CPU的个数
    print(psutil.cpu_count())
    # 获取 CPU 的物理核心数量
    print(psutil.cpu_count(logical=False))
    print(psutil.cpu_times())

    # 查看 CPU 的使用率:percpu为True时显示所有物理核心的利用率,interval不为0时,则阻塞时显示interval执行的时间内的平均利用率
    for x in range(3):
        # interval:表示每隔0.5s刷新一次
        # percpu:表示查看所有的cpu使用率
        print(psutil.cpu_percent(interval=0.5, percpu=True))
    # 查看 CPU 的统计信息,包括上下文切换、中断、软中断,以及系统调用次数等等
    print(psutil.cpu_stats())
    # 查看 CPU 的频率
    print(psutil.cpu_freq())

#----------------memory内存监控(linux命令:free)----------------
    # 查看内存使用情况:以命名元组的形式返回内存使用情况,单位为字节
    print(psutil.virtual_memory())
    '''
    total:总物理内存
    available:可用内存,available ~free + buffers + cached
    percent:使用率: percent = (total - available) / total * 100
    used:使用的内存: used  =  total - free - buffers - cache
    free:完全没用使用内存
    active:最近被访问的内存
    inactive:长时间未被访问的内存
    buffers:缓存
    cached:缓存
    slab:内核数据结构缓存的内存
	'''
    # 查看交换内存信息:以命名元组的形式返回swap/memory使用情况,包含swap中页的换入和换出
    print(psutil.swap_memory())

#----------------disk磁盘监控(linux命令:iostat, df)----------------
    # 查看磁盘分区、磁盘使用率和磁盘 IO 信息(磁盘挂载分区信息)
    print(psutil.disk_partitions())
    '''
	device:分区
    mountpoint:挂载点
    fstype:文件系统格式(fat、ext4、 xfs)
    opts:挂载参数
	'''
    # 查看某个磁盘使用情况(需要传入一个路径参数)
    print(psutil.disk_usage("/dev/disk1s5s1"))
    # 查看磁盘 IO 统计信息(以命名元组的形式返回磁盘io统计信息(汇总的),包括读、写的次数,读、写的字节数等)
    print(psutil.disk_io_counters())
    # 默认返回的是所有磁盘加起来的统计信息,我们可以指定 perdisk=True,则分别列出每一个磁盘的统计信息
    print(psutil.disk_io_counters(perdisk=True))

#----------------Network网络监控(linux命令:ifconfig, who, uptime, netstat)----------------
    # 查看网卡的网络 IO 统计信息(以命名元组的形式返回当前系统中每块网卡的网络io统计信息,包括收发字节数,收发包的数量、出错的情况和删包情况。当pernic为True时,则列出所有网卡的统计信息。)
    print(psutil.net_io_counters())
    # 里面还有一个 pernic 参数, 如果为 True, 则列出所有网卡的信息
    print(psutil.net_io_counters(pernic=True))
    # 以字典的形式返回网卡的配置信息, 包括 IP 地址、Mac地址、子网掩码、广播地址等等
    print(psutil.net_if_addrs())
    # 返回网卡的详细信息, 包括是否启动、通信类型、传输速度、mtu(最大传输单元)
    print(psutil.net_if_stats())
    # 查看当前机器的网络连接(以列表的形式返回每个网络连接的详细信息(namedtuple))
    print(psutil.net_connections())
    '''
    fd:文件描述符
    family:地址簇,ipv4(AF_INET),ipv6
    type:SOCK_STREAM(tcp)、udp
    laddr:本地ip地址
    raddr
    status
    pid
    '''
    # 查看当前登录的用户信息(以命名元组的方式返回当前登陆用户的信息,包括用户名,登陆时间,终端)
    print(psutil.users())
    # 查看系统的启动时间(以时间戳的形式返回系统的启动时间)
    print(psutil.boot_time())
    print(datetime.datetime.fromtimestamp(psutil.boot_time()))

#----------------process进程管理(linux命令:ps, kill)----------------
    # 查看当前存在的所有进程的 pid(以列表的形式返回当前正在运行的进程)
    print(psutil.pids())
    # 查看某个进程是否存在
    print(psutil.pid_exists(22333))
    print(psutil.pid_exists(0))
    # 返回所有进程(Process)对象组成的迭代器
    print(psutil.process_iter())
    '''
    name:获取进程的名称

    cmdline:获取启动进程的命令行参数

    create_time:获取进程的创建时间
    uids:进程uid信息
    num_threads:开启的线程数
    exe:进程工作的绝对路径
    kill:发送SIGKILL信号结束进程
	'''
    # 根据 pid 获取一个进程对应的 Process 对象(可以使用该类的方法获取进行的详细信息,或者给进程发送信号)
    print(psutil.Process(pid=0))


if __name__ == '__main__':
    test()

4. Code example

Use python to write a monitoring script and run it on the Linux system. The monitoring requirements are as follows:

1. Display the current time

2. After the script runs, monitor for 10s and output information every second

3. Display the number of logical cores and average usage of the current system CPU

4. Display the size of the total memory (unit M), memory usage

5. Display the size of the root directory (unit M), the usage rate of the root directory

6. What is the IP address of the machine, network usage, how many m data have been sent and received

See this blog for details on the code

Guess you like

Origin blog.csdn.net/All_In_gzx_cc/article/details/128281586