[Python] Python获取CPU使用率、内存使用率、网络使用状态 →→→→→进入此内容的聊天室

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

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

这儿你可以回复上面这条便签

captcha