Python获取CPU使用率、内存使用率、网络使用状态

Python获取CPU使用率、内存使用率、网络使用状态

分类: Python 6387人阅读 评论(2) 收藏 举报

注:需要安装psutil库

源代码如下:

[python] view plain copy
  1. #    
  2. # Copyright (c) 2014, Lambo Wang, All rights reserved.    
  3. # Use of this source code is governed by a GNU v2 license that can be    
  4. # found in the LICENSE file.    
  5.   
  6. # Logs:  
  7. # Transplant to NT system by Lambo Wang, 2012-11-28    
  8. # Add function of get cpu state and get memory state by Lambo Wang,2012-11-29    
  9. # first add to Git of OSChina,2014-10-24 by Lambo Wang   
  10. """  
  11. Shows real-time NT system statistics.  
  12. Author: Lambo Wang <lambo.wang@icloud.com>  
  13. """    
  14.     
  15. import sys    
  16. import os    
  17.     
  18. import atexit    
  19. import time    
  20. import psutil    
  21.     
  22. #print "Welcome,current system is",os.name," 3 seconds late start to get data..."    
  23. time.sleep(3)    
  24.      
  25. line_num = 1    
  26.     
  27. #function of Get CPU State    
  28. def getCPUstate(interval=1):    
  29.     return (" CPU: " + str(psutil.cpu_percent(interval)) + "%")    
  30. #function of Get Memory    
  31. def getMemorystate():    
  32.     phymem = psutil.phymem_usage()    
  33.     buffers = getattr(psutil, 'phymem_buffers'lambda0)()    
  34.     cached = getattr(psutil, 'cached_phymem'lambda0)()    
  35.     used = phymem.total - (phymem.free + buffers + cached)    
  36.     line = " Memory: %5s%% %6s/%s" % (    
  37.         phymem.percent,    
  38.         str(int(used / 1024 / 1024)) + "M",    
  39.         str(int(phymem.total / 1024 / 1024)) + "M"    
  40.     )       
  41.     return line    
  42. def bytes2human(n):    
  43.     """  
  44.     >>> bytes2human(10000)  
  45.     '9.8 K'  
  46.     >>> bytes2human(100001221)  
  47.     '95.4 M'  
  48.     """    
  49.     symbols = ('K''M''G''T''P''E''Z''Y')    
  50.     prefix = {}    
  51.     for i, s in enumerate(symbols):    
  52.         prefix[s] = 1 << (i+1)*10    
  53.     for s in reversed(symbols):    
  54.         if n >= prefix[s]:    
  55.             value = float(n) / prefix[s]    
  56.             return '%.2f %s' % (value, s)    
  57.     return '%.2f B' % (n)    
  58.     
  59.     
  60. def poll(interval):    
  61.     """Retrieve raw stats within an interval window."""    
  62.     tot_before = psutil.network_io_counters()    
  63.     pnic_before = psutil.network_io_counters(pernic=True)    
  64.     # sleep some time    
  65.     time.sleep(interval)    
  66.     tot_after = psutil.network_io_counters()    
  67.     pnic_after = psutil.network_io_counters(pernic=True)    
  68.     # get cpu state    
  69.     cpu_state = getCPUstate(interval)    
  70.     # get memory    
  71.     memory_state = getMemorystate()    
  72.     return (tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state)    
  73.     
  74. def refresh_window(tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state):    
  75.     os.system("cls")    
  76.     """Print stats on screen."""    
  77.     
  78.     
  79.     #print current time #cpu state #memory    
  80.     print(time.asctime()+" | "+cpu_state+" | "+memory_state)    
  81.         
  82.     # totals    
  83.     print(" NetStates:")    
  84.     print("total bytes:           sent: %-10s   received: %s" % (bytes2human(tot_after.bytes_sent),    
  85.                                                                       bytes2human(tot_after.bytes_recv))    
  86.     )    
  87.     print("total packets:         sent: %-10s   received: %s" % (tot_after.packets_sent,   
  88.                                                                       tot_after.packets_recv)    
  89.     )  
  90.     # per-network interface details: let's sort network interfaces so    
  91.     # that the ones which generated more traffic are shown first    
  92.     print("")    
  93.     nic_names = pnic_after.keys()    
  94.     #nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)    
  95.     for name in nic_names:    
  96.         stats_before = pnic_before[name]    
  97.         stats_after = pnic_after[name]    
  98.         templ = "%-15s %15s %15s"    
  99.         print(templ % (name, "TOTAL""PER-SEC"))    
  100.         print(templ % (    
  101.             "bytes-sent",    
  102.             bytes2human(stats_after.bytes_sent),    
  103.             bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + '/s',    
  104.         ))    
  105.         print(templ % (    
  106.             "bytes-recv",    
  107.             bytes2human(stats_after.bytes_recv),    
  108.             bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + '/s',    
  109.         ))    
  110.         print(templ % (    
  111.             "pkts-sent",    
  112.             stats_after.packets_sent,    
  113.             stats_after.packets_sent - stats_before.packets_sent,    
  114.         ))    
  115.         print(templ % (    
  116.             "pkts-recv",    
  117.             stats_after.packets_recv,    
  118.             stats_after.packets_recv - stats_before.packets_recv,    
  119.         ))    
  120.         print("")    
  121.     
  122. try:    
  123.     interval = 0    
  124.     while 1:    
  125.         args = poll(interval)    
  126.         refresh_window(*args)  
  127.         interval = 1    
  128. except (KeyboardInterrupt, SystemExit):    
  129.     pass  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值