psutil查询指定程序pid的cpu、内存使用;pgrep命令查询具体进程号、top查询具体进程的cpu、内存使用

参考:https://zhuanlan.zhihu.com/p/56478855
https://www.cnblogs.com/luchenhui/p/10974745.html

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等操作系统.

查具体某个程序的pid

通过pids和正则匹配,可以通过name或command信息去赛选在这里插入图片描述

import psutil

pids = psutil.pids()
print(len(pids))
for pid in pids:
  p = psutil.Process(pid)
  if "python ***.py" in p.cmdline():
       操作,得到具体的pid
  if 'python' in p.name():
      print("pid-%d,pname-%s" % (pid, p.name()),p.cmdline())

cpu、内存使用

监控cpu信息

import psutil psutil.cpu_times() #获取cpu(逻辑cpu的平均)占用时间的详细信息
psutil.cpu_times(percpu=True) #获取每个cpu占用时间的详细信息
psutil.cpt_times().user #获取用户进程占用cpu的时间(user+sys+idle+wait=total)

监控内存信息

import psutil psutil.virtual_memory() #获取内存信息
psutil.virtual_memory().total #获取内存总量 psutil.swap_memory()
#获取swap信息 psutil.swqp_memory() #获取swap总量

每分钟打印

import psutil
##cpu
psutil.cpu_times()
##内存
mem = psutil.virtual_memory()
import psutil
import time

pids = psutil.pids()
print(len(pids))


try:

    for pid in pids:
        p = psutil.Process(pid)
        command = p.cmdline()

        print(pid,command)
        if "/usr/bin/python3" in command and "upload_aid" in command:
            interval = 10 # polling seconds
            with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f:
                f.write("time,cpu%,mem%\n")
                while True:

                    current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
                    cpu_percent = p.cpu_percent()
                    mem_percent = p.memory_percent()
                    line = current_time + ',' + str(cpu_percent) + ',' + str(mem_percent)
                    print (line)
                    f.write(line + "\n")
                    time.sleep(interval)
                    
                    
except Exception as e:
    print(e)
    pass

磁盘、网络、温度等其他指标

import psutil

def get_system_usage():
    # 获取CPU使用率
    cpu_usage = psutil.cpu_percent(interval=1)
    print(f"CPU使用率: {cpu_usage}%")

    # 获取内存使用情况
    memory_info = psutil.virtual_memory()
    print(f"总内存: {memory_info.total} bytes")
    print(f"可用内存: {memory_info.available} bytes")
    print(f"内存使用率: {memory_info.percent}%")

    # 获取磁盘使用情况
    disk_info = psutil.disk_usage('/')
    print(f"总磁盘空间: {disk_info.total} bytes")
    print(f"已用磁盘空间: {disk_info.used} bytes")
    print(f"可用磁盘空间: {disk_info.free} bytes")
    print(f"磁盘使用率: {disk_info.percent}%")

    # 获取网络接口的统计信息
    net_io = psutil.net_io_counters()
    print(f"发送的字节数: {net_io.bytes_sent}")
    print(f"接收的字节数: {net_io.bytes_recv}")
    print(f"发送的包数: {net_io.packets_sent}")
    print(f"接收的包数: {net_io.packets_recv}")

    # 获取所有进程的PID
    pids = psutil.pids()
    print(f"当前运行的进程数: {len(pids)}")

    # 获取某个进程的信息
    if pids:
        process = psutil.Process(pids[0])
        print(f"进程名: {process.name()}")
        print(f"进程状态: {process.status()}")
        print(f"进程CPU使用率: {process.cpu_percent(interval=1)}%")
        print(f"进程内存使用率: {process.memory_percent()}%")

    # 获取磁盘I/O统计信息
    disk_io = psutil.disk_io_counters()
    print(f"读取的字节数: {disk_io.read_bytes}")
    print(f"写入的字节数: {disk_io.write_bytes}")
    print(f"读取的次数: {disk_io.read_count}")
    print(f"写入的次数: {disk_io.write_count}")

    # 获取温度信息
    sensors_temperatures = psutil.sensors_temperatures()
    if sensors_temperatures:
        for name, entries in sensors_temperatures.items():
            print(f"传感器: {name}")
            for entry in entries:
                print(f"  温度: {entry.current}°C")

    # 获取风扇速度信息
    sensors_fans = psutil.sensors_fans()
    if sensors_fans:
        for name, entries in sensors_fans.items():
            print(f"风扇: {name}")
            for entry in entries:
                print(f"  速度: {entry.current} RPM")

    # 获取电池信息
    battery = psutil.sensors_battery()
    if battery:
        print(f"电池百分比: {battery.percent}%")
        print(f"电池是否在充电: {battery.power_plugged}")

if __name__ == "__main__":
    get_system_usage()

2、pgrep命令查询具体进程号、top查询具体进程的cpu、内存使用

参考:https://www.python100.com/html/72141.html

pgrep查进程:

pgrep -f [进程关键字]

在这里插入图片描述
top查询具体进程的cpu、内存使用:

top -p [进程id]

在这里插入图片描述
在这里插入图片描述

top查询的的具体进程的cpu、内存使用循环打印保存txt:

top -d 1 -b -p 1234 | awk 'NR>6 { print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }' >> top_output.txt

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

loong_XL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值