在linux中直接使用“top”命令查詢:第三行就是關於CPU的信息
[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
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())