zoukankan      html  css  js  c++  java
  • python调用top命令获得CPU利用率

    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('
    
    
    ')[1].split('
    ')[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('
    
    
    ')[1].split('
    ')[2])
            time.sleep(time2sleep)
  • 相关阅读:
    中文分词算法工具hanlp源码解析
    Hanlp分词1.7版本在Spark中分布式使用记录
    Window离线环境下如何安装pyhanlp
    如何编译运行HanLP自然语言处理包
    函数调用面试题
    构造函数复习
    面向对象的好处
    递归实现查找页面所有节点
    面向对象和原型
    chrome浏览器调试工具的使用
  • 原文地址:https://www.cnblogs.com/nulige/p/7797210.html
Copyright © 2011-2022 走看看