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

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 05:19   66   0

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

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

注:需要安装psutil库

源代码如下:

  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. import sys
  15. import os
  16. import atexit
  17. import time
  18. import psutil
  19. #print "Welcome,current system is",os.name," 3 seconds late start to get data..."
  20. time.sleep(3)
  21. line_num = 1
  22. #function of Get CPU State
  23. def getCPUstate(interval=1):
  24. return (" CPU: " + str(psutil.cpu_percent(interval)) + "%")
  25. #function of Get Memory
  26. def getMemorystate():
  27. phymem = psutil.phymem_usage()
  28. buffers = getattr(psutil, 'phymem_buffers', lambda: 0)()
  29. cached = getattr(psutil, 'cached_phymem', lambda: 0)()
  30. used = phymem.total - (phymem.free + buffers + cached)
  31. line = " Memory: %5s%% %6s/%s" % (
  32. phymem.percent,
  33. str(int(used / 1024 / 1024)) + "M",
  34. str(int(phymem.total / 1024 / 1024)) + "M"
  35. )
  36. return line
  37. def bytes2human(n):
  38. """
  39. >>> bytes2human(10000)
  40. '9.8 K'
  41. >>> bytes2human(100001221)
  42. '95.4 M'
  43. """
  44. symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
  45. prefix = {}
  46. for i, s in enumerate(symbols):
  47. prefix[s] = 1 << (i+1)*10
  48. for s in reversed(symbols):
  49. if n >= prefix[s]:
  50. value = float(n) / prefix[s]
  51. return '%.2f %s' % (value, s)
  52. return '%.2f B' % (n)
  53. def poll(interval):
  54. """Retrieve raw stats within an interval window."""
  55. tot_before = psutil.network_io_counters()
  56. pnic_before = psutil.network_io_counters(pernic=True)
  57. # sleep some time
  58. time.sleep(interval)
  59. tot_after = psutil.network_io_counters()
  60. pnic_after = psutil.network_io_counters(pernic=True)
  61. # get cpu state
  62. cpu_state = getCPUstate(interval)
  63. # get memory
  64. memory_state = getMemorystate()
  65. return (tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state)
  66. def refresh_window(tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state):
  67. os.system("cls")
  68. """Print stats on screen."""
  69. #print current time #cpu state #memory
  70. print(time.asctime()+" | "+cpu_state+" | "+memory_state)
  71. # totals
  72. print(" NetStates:")
  73. print("total bytes: sent: %-10s received: %s" % (bytes2human(tot_after.bytes_sent),
  74. bytes2human(tot_after.bytes_recv))
  75. )
  76. print("total packets: sent: %-10s received: %s" % (tot_after.packets_sent,
  77. tot_after.packets_recv)
  78. )
  79. # per-network interface details: let's sort network interfaces so
  80. # that the ones which generated more traffic are shown first
  81. print("")
  82. nic_names = pnic_after.keys()
  83. #nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
  84. for name in nic_names:
  85. stats_before = pnic_before[name]
  86. stats_after = pnic_after[name]
  87. templ = "%-15s %15s %15s"
  88. print(templ % (name, "TOTAL", "PER-SEC"))
  89. print(templ % (
  90. "bytes-sent",
  91. bytes2human(stats_after.bytes_sent),
  92. bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
  93. ))
  94. print(templ % (
  95. "bytes-recv",
  96. bytes2human(stats_after.bytes_recv),
  97. bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
  98. ))
  99. print(templ % (
  100. "pkts-sent",
  101. stats_after.packets_sent,
  102. stats_after.packets_sent - stats_before.packets_sent,
  103. ))
  104. print(templ % (
  105. "pkts-recv",
  106. stats_after.packets_recv,
  107. stats_after.packets_recv - stats_before.packets_recv,
  108. ))
  109. print("")
  110. try:
  111. interval = 0
  112. while 1:
  113. args = poll(interval)
  114. refresh_window(*args)
  115. interval = 1
  116. except (KeyboardInterrupt, SystemExit):
  117. pass
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP