Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 205|回复: 0

[默认分类] Python获取CPU使用率、内存使用率、网络使用状态

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-6-12 11:17:30 | 显示全部楼层 |阅读模式


    注:需要安装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 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. # support for psutil(v3.2.2),2015-11-12 by Lambo Wang
    11. """   
    12. Shows real-time system statistics.   
    13. Author: Lambo Wang <lambo.wang@icloud.com>   
    14. """
    15. import sys
    16. import os
    17. import atexit
    18. import time
    19. import psutil
    20. #print "Welcome,current system is",os.name," 3 seconds late start to get data..."   
    21. time.sleep(3)
    22. line_num = 1
    23. #function of Get CPU State;
    24. def getCPUstate(interval=1):
    25.     return (" CPU: " + str(psutil.cpu_percent(interval)) + "%")   
    26. #function of Get Memory   
    27. def getMemorystate():
    28.         phymem = psutil.virtual_memory()
    29.         line = "Memory: %5s%% %6s/%s"%(
    30.             phymem.percent,
    31.             str(int(phymem.used/1024/1024))+"M",
    32.             str(int(phymem.total/1024/1024))+"M"
    33.             )
    34.         return line   
    35. def bytes2human(n):   
    36.         """   
    37.         >>> bytes2human(10000)   
    38.         "9.8 K"   
    39.         >>> bytes2human(100001221)   
    40.         "95.4 M"   
    41.         """   
    42.         symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")   
    43.         prefix = {}   
    44.         for i, s in enumerate(symbols):   
    45.                 prefix[s] = 1 << (i+1)*10   
    46.         for s in reversed(symbols):   
    47.                 if n >= prefix[s]:   
    48.                         value = float(n) / prefix[s]   
    49.                         return "%.2f %s" % (value, s)   
    50.         return "%.2f B" % (n)   
    51.       
    52.       
    53. def poll(interval):   
    54.         """Retrieve raw stats within an interval window."""   
    55.         tot_before = psutil.net_io_counters()   
    56.         pnic_before = psutil.net_io_counters(pernic=True)   
    57.         # sleep some time   
    58.         time.sleep(interval)   
    59.         tot_after = psutil.net_io_counters()   
    60.         pnic_after = psutil.net_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.       
    67. def refresh_window(tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state):   
    68.         if os.name == "nt":
    69.             os.system("cls")   
    70.         else:
    71.             os.system("clear")   
    72.         """Print stats on screen."""   
    73.       
    74.       
    75.         #print current time #cpu state #memory   
    76.         print(time.asctime()+" | "+cpu_state+" | "+memory_state)   
    77.               
    78.         # totals   
    79.         print(" NetStates:")   
    80.         print("total bytes:                     sent: %-10s     received: %s" % (bytes2human(tot_after.bytes_sent),   
    81.                                                                                                                                             bytes2human(tot_after.bytes_recv))   
    82.         )   
    83.         print("total packets:                 sent: %-10s     received: %s" % (tot_after.packets_sent,   
    84.                                                                                                                                             tot_after.packets_recv)   
    85.         )
    86.         # per-network interface details: let"s sort network interfaces so   
    87.         # that the ones which generated more traffic are shown first   
    88.         print("")   
    89.         nic_names = pnic_after.keys()   
    90.         #nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)   
    91.         for name in nic_names:   
    92.                 stats_before = pnic_before[name]   
    93.                 stats_after = pnic_after[name]   
    94.                 templ = "%-15s %15s %15s"   
    95.                 print(templ % (name, "TOTAL", "PER-SEC"))   
    96.                 print(templ % (   
    97.                         "bytes-sent",   
    98.                         bytes2human(stats_after.bytes_sent),   
    99.                         bytes2human(stats_after.bytes_sent - stats_before.bytes_sent) + "/s",   
    100.                 ))   
    101.                 print(templ % (   
    102.                         "bytes-recv",   
    103.                         bytes2human(stats_after.bytes_recv),   
    104.                         bytes2human(stats_after.bytes_recv - stats_before.bytes_recv) + "/s",   
    105.                 ))   
    106.                 print(templ % (   
    107.                         "pkts-sent",   
    108.                         stats_after.packets_sent,   
    109.                         stats_after.packets_sent - stats_before.packets_sent,   
    110.                 ))   
    111.                 print(templ % (   
    112.                         "pkts-recv",   
    113.                         stats_after.packets_recv,   
    114.                         stats_after.packets_recv - stats_before.packets_recv,   
    115.                 ))   
    116.                 print("")   
    117.       
    118. try:   
    119.         interval = 0   
    120.         while 1:   
    121.                 args = poll(interval)   
    122.                 refresh_window(*args)
    123.                 interval = 1   
    124. except (KeyboardInterrupt, SystemExit):   
    125.         pass
    复制代码



      
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-24 10:38 , Processed in 0.528237 second(s), 35 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表