获取linux的剩余cpu

在linux中直接使用“top”命令查询:第三行就是关于CPU的信息

参考链接:https://blog.csdn.net/yjclsx/article/details/81508455 Linux中top命令参数详解

[root@CTDI testzq]# top
top - 22:03:22 up 12 days, 10:13,  2 users,  load average: 0.23, 0.23, 0.25
Tasks: 178 total,   1 running, 177 sleeping,   0 stopped,   0 zombie
%Cpu(s):  8.8 us,  0.3 sy,  0.0 ni, 91.4 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
KiB Mem : 16268356 total,  2715284 free,  6874236 used,  6678836 buff/cache
KiB Swap:  8388604 total,  8369176 free,    19428 used.  8640692 avail Mem

PID   USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
1733  mysql     20   0 2646916 442212   8356 S  27.7  2.7   3696:03 mysqld
7230  ctdi      20   0  752312  67788   5376 S   0.7  0.4   1:12.49 python

获取使用的CPU使用占比:

import os
import re 

def get_cpuinfo():
   cpupercent=0
   liststr = os.popen('top -bi -n 1').read().split('\n')[2]        #第三行:%Cpu(s):  8.0 us,  0.5 sy,  0.0 ni, 91.4 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
   cpudata = re.findall(r'-?\d+\.?\d*e?-?\d*?',liststr)             #['8.0', '0.5', '0.0', '91.4', '0.0', '0.0', '0.1', '0.0']

   cpupercent = 100 - eval(cpudata[3])
   return  cpupercent

print(get_cpuinfo())

或者:

import os
import re
def get_cpuinfo():
        liststr = os.popen('top -bi -n 1').read().split('\n')[2]
        #cpudata = re.findall(r'-?\d+\.?\d*e?-?\d*?',liststr)
        cpudata = liststr.split(',')[3].strip()
        print(cpudata)
        cpupercent = 100 - eval(cpudata[:-3])
        return  cpupercent
print(get_cpuinfo())

获取内存使用占比:

memstr = os.popen("free").read().split('\n')[1]                    #'Mem:       16266796     5770032     9354084       18168     1142680    10147096'
memdata = re.findall(r"\d+", memstr)                               #['16266796', '5770032', '9354084', '18168', '1142680', '10147096']
memusedpercent = '%.5f' % (100 * (float(memdata[1]) / float(memdata[0])))

 

项目测试:

# -*- coding: utf-8 -*-
import os
import re
import time
from .. import Engine

def get_cpu_mem_info():
    #获取CPU占用比信息
    cpustr = os.popen('top -bi -n 1').read().split('\n')[2]             #第三行:%Cpu(s):  8.0 us,  0.5 sy,  0.0 ni, 91.4 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
    cpudata = re.findall(r'-?\d+\.?\d*e?-?\d*?',cpustr)                 #['8.0', '0.5', '0.0', '91.4', '0.0', '0.0', '0.1', '0.0']
    cpupercent = '%.5f' %(100 - eval(cpudata[3]))
   
    # 获取内存信息
    memstr = os.popen("free").read().split('\n')[1]                    #'Mem:       16266796     5770032     9354084       18168     1142680    10147096'
    memdata = re.findall(r"\d+", memstr)                               #['16266796', '5770032', '9354084', '18168', '1142680', '10147096']
    mempercent = '%.5f' % (100 * (float(memdata[1]) / float(memdata[0])))
    return {"cpupercent": cpupercent,"mempercent":mempercent,"memtotal":memdata[0],"memused":memdata[1],"memfree":memdata[2]}



all_cpu_mem_file = '../test_scripts/all_cpu_mem.csv'         #配置日志路径和名字
allinitdata = 'processid,cpu%,mem%,memtotal,memused,memfree,time'                            #文件头信息
delta_cpu_mem_file = '../test_scripts/delta_cpu_mem.csv'
deltainitdata = 'processid,delta_cpu%,delta_mem%,delta_memused,time'


#获取当前的cpu、内存信息写入文件
def current_cpu_mem(pid,cpu_mem_info):
    cpupercent = cpu_mem_info["cpupercent"]
    mempercent = cpu_mem_info["mempercent"]
    memtotal = cpu_mem_info["memtotal"]
    memused = cpu_mem_info["memused"]
    memfree = cpu_mem_info["memfree"]
    currenttime = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
    if not os.path.exists(all_cpu_mem_file):
        with open(all_cpu_mem_file, 'w') as f:
            f.write(allinitdata)
            f.write('\n')
    wdata = str(pid)+','+cpupercent+','+mempercent+','+memtotal+','+memused+','+memfree+','+currenttime
    with open(all_cpu_mem_file, 'a+') as f:
        f.write(wdata)
        f.write('\n')


#获取一段程序间所消耗的cpu与内存资源
def delta_cpu_mem(pid,begine_cpu_mem,end_cpu_mem):
    delta_cpupercent = float(begine_cpu_mem["cpupercent"]) - float(end_cpu_mem["cpupercent"])
    delta_mempercent = float(begine_cpu_mem["mempercent"]) - float(end_cpu_mem["mempercent"])
    delta_memused = float(end_cpu_mem["memused"]) - float(begine_cpu_mem["memused"])
    currenttime = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
    if not os.path.exists(delta_cpu_mem_file):
        with open(delta_cpu_mem_file, 'w') as f:
            f.write(deltainitdata)
            f.write('\n')
    wdata = str(pid)+','+str(delta_cpupercent)+','+str(delta_mempercent)+','+str(delta_memused)+','+currenttime
    with open(delta_cpu_mem_file, 'a+') as f:
        f.write(wdata)
        f.write('\n')


#测试代码
def test_engine():
    begine_cpu_mem = get_cpu_mem_info()
    current_cpu_mem(os.getpid(), begine_cpu_mem)
    Engine()
    end_cpu_mem = get_cpu_mem_info()
    current_cpu_mem(os.getpid(), end_cpu_mem)
    delta_cpu_mem(os.getpid(), begine_cpu_mem, end_cpu_mem)

if __name__ == '__main__':
    test_engine()

 

 

 

你可能感兴趣的:(linux,python,linux,cpu,mem)