python-进程服务psutil

psutil模块

概述

psutil = process and system utilities,

能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理,能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。

安装

git clone https://github.com/giampaolo/psutil.git
cd psutil
python setup.py install


pip3 install psutil

CPU

函数 描述
psutil.cpu_count() cpu_count(,[logical]):默认返回逻辑CPU的个数,当设置logical的参数为False时,返回物理CPU的个数。
psutil.cpu_percent() cpu_percent(,[percpu],[interval]):返回CPU的利用率,percpu为True时显示所有物理核心的利用率,interval不为0时,则阻塞时显示interval执行的时间内的平均利用率
psutil.cpu_times() cpu_times(,[percpu]):以命名元组(namedtuple)的形式返回cpu的时间花费,percpu=True表示获取每个CPU的时间花费
psutil.cpu_times_percent() cpu_times_percent(,[percpu]):功能和cpu_times大致相同,看字面意思就能知道,该函数返回的是耗时比例。
psutil.cpu_stats() cpu_stats()以命名元组的形式返回CPU的统计信息,包括上下文切换,中断,软中断和系统调用次数。
psutil.cpu_freq() cpu_freq([percpu]):返回cpu频率
# 查看cpu个数
import psutil
cpu_count=psutil.cpu_count()
print(cpu_count)
-> 2

cpu_count=psutil.cpu_count(logical=False)
print(cpu_count)
-> 1

# 查看cpu利用率
cpu_percent=psutil.cpu_percent()
print(cpu_percent)
-> 0.2
cpu_percent=psutil.cpu_percent(percpu=True)
print(cpu_percent)
-> [0.1, 0.2]

# 查看cpu时间花费
cpu_times=psutil.cpu_times()
print(cpu_times)
#-> scputimes(user=9900.40625, system=10337.078125, idle=660792.265625, interrupt=737.8125, dpc=939.296875)

cpu_times=psutil.cpu_times(percpu=True)
print(cpu_times)
#-> [scputimes(user=13.64, nice=0.0, system=12.02, idle=12235.5, iowait=1.0, irq=0.0, softirq=0.16, steal=0.09, guest=0.0, guest_nice=0.0), scputimes(user=15.47, nice=0.0, system=10.62, idle=12229.44, iowait=0.74, irq=0.0, softirq=0.12, steal=0.17, guest=0.0, guest_nice=0.0)]

#user:用户进程花费的时间
#nice:用户模式执行Niced优先级进程花费的时间
#system:内核模式进程花费的时间
#idle:闲置时间
#iowait:等待I/O完成的时间
#irq:处理硬件中断的时间
#softirq:处理软件中断的时间
#steal:虚拟化环境中运行的其他操作系统花费的时间
#guest:在linux内核的控制下为客户端操作系统运行虚拟CPU所花费的时间
#guest_nice:虚拟机运行niced所花费的时间


print(psutil.cpu_stats())
#-> scpustats(ctx_switches=1425247028, interrupts=897353367, soft_interrupts=0, syscalls=3536538419)

# 频率
print(psutil.cpu_freq())
#-> scpufreq(current=3301.0, min=0.0, max=3301.0)

内存

virtual_memory()

#以命名元组的形式返回内存使用情况,包括总内存,可用内存,内存利用率,buffer和cache等。单位为字节

import psutil
mem = psutil.virtual_memory()
print(mem)

# svmem(total=15968038912, available=6411112448, percent=59.9, used=9556926464, free=6411112448)

#total:总物理内存
#available:可用的内存
#used:使用的内存
#free:完全没有使用的内存
#active:当前正在使用的内存
#inactive:标记为未使用的内存
#buffers:缓存文件系统元数据使用的内存
#cached:缓存各种文件的内存
#shared:可以被多个进程同时访问的内存
#slab:内核数据结构缓存的内存
# 内存
mem = psutil.virtual_memory()

percent=mem.percent
print(percent)      # int
# 59.4

total=mem.total
used=mem.used
free=mem.free

print(total,"B")
print(used,"B")
print(free,"B")

#15968038912 B
#9404264448 B
#6563774464 B

total=mem.total/NUM_Bit2Mb
used=mem.used/NUM_Bit2Mb
free=mem.free/NUM_Bit2Mb
print(total,"M")
print(used,"M")
print(free,"M")
#15228.30859375 M
#8968.60546875 M
#6259.703125 M

swap_memory()

import psutil
swap_memory=psutil.swap_memory()

# sswap(total=17179865088, used=0, free=17179865088, percent=0.0, sin=0, sout=0)

进程管理

函数 说明
psutil.pids() 返回当前正在运行的进程,返回列表
psutil.pid_exists(1) 判断给点定的pid是否存在,返回布尔值
psutil.process_iter() 迭代当前正在运行的进程,返回的是每个进程的Process对象
psutil.Process() 查看单个进程,可以使用该类的方法获取进行的详细信息,或者给进程发送信号。

通过进程号实例化对象

p = psutil.Process(pid) 相关信息和方法

方法 说明
p.pid 进程PID
p.name() 获取进程的名称
p.cmdline() 获取启动进程的命令行参数
p.exe() 进程的bin路径,环境目录
p.cwd() 进程的工作目录绝对路径
p.uids() 进程uid信息
p.gids() 进程的gid信息
p.parent() 父进程对象
p.ppid() 父进程PID
p.children() 当前进程的子进程列表
p.num_threads() 进程开启的线程数
p.cpu_times() 进程的cpu时间信息
p.cpu_percent() 当前进程CPU利用率
p.memory_info() 进程内存信息
p.memory_persent() 进程内存占比
p.status() 进程当前状态
p.username() 进程用户名
p.terminal() 进程终端
p.is_running() 进程是否还在运行
p.create_time() 进程创建时间
p.open_files() 进程打开的文件
p.num_fds() 进程打开的文件个数
p.terminate() SIGTERM提前终止进程
p.kill() SIGKILL预先终止当前进程
import psutil

print(psutil.pids())
# [0, 4, 8, 148, 508, 624, 884, 896, 1160, 1240, 1288, 1336, 1444, 1460, 1536, 1548, 1616, 1636, 1708, 1844, 1900, 1936, 1952, 1972, 2000, 2028, 2040, 2060, 2132, 2212, 2220, 2236, 2248, 2260, 2276]

print(psutil.process_iter())   # 返回生成器
print(list(psutil.process_iter())[0])
#<generator object process_iter at 0x000001DEF53629C8>
#psutil.Process(pid=0, name='System Idle Process', status='running')

psutil.Process()


p.name()                         # 进程名
p.exe()                          # 进程的bin路径
p.cwd()                          # 进程的工作目录绝对路径
p.cmdline()						 # 进程的启动命令行参数


p.create_time()                  # 进程创建时间
p.uids()                         # 进程uid信息
p.gids()                         # 进程的gid信息

p.parent()						 # 父进程对象
p.ppid()					     # 父进程PID
p.children()	                 # 当前进程的子进程列表


p.cpu_times()                    # 进程的cpu时间信息,包括user,system两个cpu信息
p.cpu_affinity()                 # get进程cpu亲和度,如果要设置cpu亲和度,将cpu号作为参考就好
p.cpu_percent(interval=1)      # 查看多少秒的进程cpu占用 interval后面跟秒

p.memory_percent()               # 进程内存利用率
p.memory_info()                  # 进程内存rss,vms信息

p.io_counters()                  # 进程的IO信息,包括读写IO数字及参数
p.connectios()                   # 返回进程列表
p.num_threads()                  # 进程开启的线程数


p.status()                       # 进程状态
p.is_running()                   # 是否正在运行

p.create_time() 				 # 进程创建时间

磁盘

import psutil

disK=psutil.disk_partitions(all=False) #获取磁盘完整信息
print(disk)
 
# [sdiskpart(device='/dev/vda1', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro,data=ordered', maxfile=255, maxpath=4096), sdiskpart(device='/dev/vdb', mountpoint='/mnt/datadisk0', fstype='ext4', opts='rw,relatime,data=ordered', maxfile=255, maxpath=4096)]


disk_usage=psutil.disk_usage('/')
print(disk_usage)
# sdiskusage(total=52776349696, used=50000330752, free=526090240, percent=99.0

#total:总的大小(字节)
#used:已使用的大小(字节)
#free:空闲的大小(字节)
#percent:使用百分比

磁盘容量示例:

# 输出当前分区挂载详情
disk_partitions = psutil.disk_partitions()
# 循环列表
for i in disk_partitions:
    # 分区设备名称
    print(i[0])
    # 分区挂载点
    print(i[1])
    # 分区格式类型
    print(i[2])
    # 分区所属权限
    print(i[3])

# 指定挂载分区大小
disk_usage = psutil.disk_usage('/')
disk_usage = psutil.disk_usage('/data')


Mem_Bit2GB=1024*1024*1024
# 挂载磁盘总大小
disk_total = str(disk_usage.total/Mem_Bit2GB) + " GB"
print(disk_total)

# 挂载磁盘使用空间
disk_used = str(disk_usage.used/Mem_Bit2GB) + " GB"
print(disk_used)

# 挂载磁盘剩余空间
disk_free = str(disk_usage.free/Mem_Bit2GB) + " GB"
print(disk_free)

网络

查看网卡

psutil.net_if_addrs().keys()
for i in psutil.net_if_addrs().keys():
    network = networkapi[i]
    print("网卡IP地址:", network[0][1])
    print("子网地址:", network[0][2])
    print("网卡MAC地址:", network[1][1])

输出网络每个接口信息

psutil.net_io_counters(pernic=True)     #pernic=True

案例

# 获取网络信息
ionetwork = psutil.net_io_counters()# 发送总字节数
iobytes_sent = ionetwork.bytes_sent

# 接收总字节数
iobytes_recv = ionetwork.bytes_recv

# 发送总包个数
netpackets_sent = ionetwork.packets_sent

# 接收总包个数
netpackets_recv = ionetwork.packets_recv

# 接收错误数
errin = ionetwork.errin

# 发送错误数
errout = ionetwork.errout

# 求其传入数据包数量
dropin = ionetwork.dropin

# 丢弃传输数据包数量
dropout = ionetwork.dropout# 求出每秒的网络信息
t1_net = psutil.net_io_counters()
time.sleep(1)
t2_net = psutil.net_io_counters()# 求出每秒发送网卡流量
bytes_sent = t2_net.bytes_sent - t1_net.bytes_sent
bytes_sent = str(int(bytes_sent)/1024) + " KB"
print(bytes_sent)

# 求出每秒接收网卡流量
bytes_recv = t2_net.bytes_recv - t1_net.bytes_recv
bytes_recv = str(int(bytes_recv)/1024) + " KB"
print(bytes_recv)

# 求出每秒发送包的数量
packets_sent = t2_net.packets_sent - t1_net.packets_sent
print(packets_sent)

# 求出每秒接收报的数量
packets_recv = t2_net.packets_recv - t1_net.packets_recv
print(packets_recv)

其他系统信息

获取当前系统用户登录信息

psutil.users()
user = psutil.users()
for i in user:
    if i.terminal == a:

        # 获取用户名
        username = i.name
        print("用户名:", username)

        # 虚拟终端
        terminal = i.terminal
        print("虚拟终端:", terminal)

        # 连接地址
        host = i.host
        print("连接地址:", host)

        # 以使用时间
        started = i.started
        print("使用时间:", started)

        # 用户pid
        userpid = i.pid 

获取开机时间

import psutil,time
psutil.boot_time()  #系统启动时间戳
1527457908.0
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(psutil.boot_time
    ...: ()))    #格式化时间
'2018-05-28 05:51:48'

psutil.users()   #返回当前链接的系统用户
 
# [suser(name='root', terminal='tty1', host='', started=1527050368.0, pid=769), suser(name='root', terminal='pts/0', host='192.168.146.1', started=1527559040.0, pid=122742),suser(name='root', terminal='pts/1', host='192.168.146.1', started=1527559040.0, pid=122761)]
posted @ 2021-09-12 19:50  贝壳里的星海  阅读(1019)  评论(0编辑  收藏  举报