python調用top命令得到CPU利用率

一、python調用top命令得到CPU利用率python

思路:經過python調用top命令獲取cpu使用率spa

#python2代碼code

[root@zdops-server script]# cat cpu_loadavg.py 
#!/usr/bin/env python
# -*- coding:utf-8 -*- 
#Author: nulige

import os,time
time2sleep = 2.5
while True:
        print int(time.time()),
        print os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[1].split('\n')[2]
        time.sleep(time2sleep)

執行結果:server

[root@zdops-server script]# python cpu_loadavg.py 
1510012411 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012414 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012417 Cpu(s): 25.0%us, 25.0%sy,  0.0%ni, 50.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012420 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012423 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012426 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012429 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012432 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012435 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012438 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012441 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012444 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012447 Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
1510012450 Cpu(s):  0.0%us, 33.3%sy,  0.0%ni, 66.7%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

#python3代碼blog

[root@zdops-server script]# cat cpu_loadavg.py     ip

#!/usr/bin/env python
# -*- coding:utf-8 -*- 
#Author: nulige

import os,time
time2sleep = 2.5
while True:
        print (int(time.time())),
        print (os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[1].split('\n')[2])
        time.sleep(time2sleep)
相關文章
相關標籤/搜索