1、python调用top命令获得CPU利用率
思路:通过python调用top命令获取cpu使用率
#python2代码
[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)
执行结果:
[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代码
[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)