Python获取CPU、内存使用率以及网络使用状态代码


Posted in Python onFebruary 08, 2018

由于psutil已更新到3.0.1版本,最新的代码如下:

#!/usr/bin/env python

import os
import time
import sys
import atexit
import psutil

#print "Welcome,current system is",os.name," 3 seconds late start to get data"
time.sleep(3)

line_num = 1

#function of Get cpu state
def getCPUstate(interval=1):
  return (" CPU:"+str(psutil.cpu_percent(interval))+"%")

def getMemorystate():
  phymem = psutil.virtual_memory()
  line = "Memory: %5s%% %6s/%s"%(
      phymem.percent,
      str(int(phymem.used/1024/1024))+"M",
      str(int(phymem.total/1024/1024))+"M"
      )
  return line
def bytes2human(n):
  """
  >>>bytes2human(10000)
  '9.8k'
  >>>bytes2human(100001221)
  '95.4M'
  """
  symbols = ('K','M','G','T','P','E','Z','Y')
  prefix = {}
  for i ,s in enumerate(symbols):
    prefix[s] = 1 << (i+1)*10
  for s in reversed(symbols):
    if n >=prefix[s]:
      value = float(n) / prefix[s]
      return '%.2f %s'%(value,s)
  return '%.2fB'%(n)
def poll(interval):
  """Retrieve raw stats within an interval window."""
  tot_before = psutil.net_io_counters()
  pnic_before = psutil.net_io_counters(pernic=True)
  #sleep some time
  time.sleep(interval)
  tot_after = psutil.net_io_counters()
  pnic_after = psutil.net_io_counters(pernic=True)
  #get cpu stats
  cpu_state = getCPUstate(interval)
  #get memory
  memory_state = getMemorystate()
  return (tot_before,tot_after,pnic_before,pnic_after,cpu_state,memory_state)
def refresh_window(tot_before,tot_after,pnic_before,pnic_after,cpu_state,memory_state):
  """print stats on screen"""
  #print current time,cpu state,memory
  print (time.asctime() +" | "+cpu_state+" | "+
      memory_state)
  #total
  print(" NetStates:")
  print(" total bytes: sent: %-10s received: %s"%(\
    bytes2human(tot_after.bytes_sent), \
    bytes2human(tot_after.bytes_recv)))
  print( " total packets: sent: %-10s received: %s"%(\
    tot_after.packets_sent,\
    tot_after.packets_recv))
  # per-network interface details: let's sort network interfaces so  
  # that the ones which generated more traffic are shown first
  print( " ")
  nic_names = pnic_after.keys()
  #nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
  for name in nic_names:
    stats_before = pnic_before[name]
    stats_after = pnic_after[name]
    templ = "%-15s %15s %15s"  
    print(templ % (name, "TOTAL", "PER-SEC")) 
    print(templ % (
      "bytes-sent",  
      bytes2human(stats_after.bytes_sent), 
      bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) +
      '/s', 
      ))
    print(templ % (  
      "bytes-recv",  
      bytes2human(stats_after.bytes_recv),  
      bytes2human(stats_after.bytes_recv- stats_before.bytes_recv)
      + '/s',  
      ))
    print(templ % ( 
      "pkts-sent",
      stats_after.packets_sent,
      stats_after.packets_sent - stats_before.packets_sent,
      ))
    print((templ %(
      "pkts-recv", 
      stats_after.packets_recv,
      stats_after.packets_recv - stats_before.packets_recv,
      )))
    print( " ")
try:
  interval = 0
  while 1:
    args = poll(interval)
    refresh_window(*args)
    interval = 1
except (KeyboardInterrupt,SystemExit):
  pass

以上就是本次更新后的实例代码,大家可以一起测试下,如果有其他问题可以在下方的留言区讨论,感谢你对三水点靠木的支持。

Python 相关文章推荐
解读Python编程中的命名空间与作用域
Oct 16 Python
python实现比较文件内容异同
Jun 22 Python
python使用thrift教程的方法示例
Mar 21 Python
Django页面数据的缓存与使用的具体方法
Apr 23 Python
PIL对上传到Django的图片进行处理并保存的实例
Aug 07 Python
python 进程的几种创建方式详解
Aug 29 Python
如何在django中添加日志功能
Feb 06 Python
python实现凯撒密码、凯撒加解密算法
Jun 11 Python
树莓派4B安装Tensorflow的方法步骤
Jul 16 Python
python爬虫beautifulsoup解析html方法
Dec 07 Python
python爬虫beautifulsoup库使用操作教程全解(python爬虫基础入门)
Feb 19 Python
Python 详解通过Scrapy框架实现爬取百度新冠疫情数据流程
Nov 11 Python
python实现二叉查找树实例代码
Feb 08 #Python
单链表反转python实现代码示例
Feb 08 #Python
Python测试人员需要掌握的知识
Feb 08 #Python
python实现单向链表详解
Feb 08 #Python
Python生成器以及应用实例解析
Feb 08 #Python
代码分析Python地图坐标转换
Feb 08 #Python
python爬虫中get和post方法介绍以及cookie作用
Feb 08 #Python
You might like
基于mysql的论坛(4)
2006/10/09 PHP
解析php中两种缩放图片的函数,为图片添加水印
2013/06/14 PHP
ThinkPHP访问不存在的模块跳转到404页面的方法
2014/06/19 PHP
smarty模板引擎之分配数据类型
2015/03/30 PHP
ThinkPHP数据操作方法总结
2015/09/28 PHP
Composer设置忽略版本匹配的方法
2016/04/27 PHP
thinkPHP框架可添加js事件的分页类customPage.class.php完整实例
2017/03/16 PHP
php file_get_contents取文件中数组元素的方法
2017/04/01 PHP
php删除数组指定元素实现代码
2017/05/03 PHP
Windows下wamp php单元测试工具PHPUnit安装及生成日志文件配置方法
2018/05/28 PHP
thinkPHP框架实现多表查询的方法
2018/06/14 PHP
学习YUI.Ext 第二天
2007/03/10 Javascript
JS实时弹出新消息提示框并有提示音响起的实现代码
2016/04/20 Javascript
JavaScript实现简单的拖动效果
2016/07/02 Javascript
JavaScript获取URL参数的方法之一
2017/03/24 Javascript
Vue 进阶教程之v-model详解
2017/05/06 Javascript
js学习总结之DOM2兼容处理this问题的解决方法
2017/07/27 Javascript
微信小程序三级联动选择器使用方法
2020/05/19 Javascript
webpack 插件html-webpack-plugin的具体使用
2018/04/09 Javascript
微信小程序使用wxParse解析html的实现示例
2018/08/30 Javascript
使用koa-log4管理nodeJs日志笔记的使用方法
2018/11/30 NodeJs
LayUi使用switch开关,动态的去控制它是否被启用的方法
2019/09/21 Javascript
Windows上使用virtualenv搭建Python+Flask开发环境
2016/06/07 Python
Python使用修饰器执行函数的参数检查功能示例
2017/09/26 Python
TensorFlow 实战之实现卷积神经网络的实例讲解
2018/02/26 Python
解决python3爬虫无法显示中文的问题
2018/04/12 Python
python 协程中的迭代器,生成器原理及应用实例详解
2019/10/28 Python
Django查询优化及ajax编码格式原理解析
2020/03/25 Python
大学毕业生通用自荐信范文
2013/10/31 职场文书
企业后勤岗位职责
2014/02/28 职场文书
建筑设计专业求职自我评价
2014/03/02 职场文书
旺仔牛奶广告词
2014/03/20 职场文书
项目合作协议书范本
2014/04/16 职场文书
毕业设计论文评语
2014/12/31 职场文书
幼儿园欢迎词范文
2015/01/26 职场文书
nginx location 带斜杠【 / 】与不带的区别
2022/04/13 Servers