Python网速监控

Python3如何监控电脑网速?

  • 使用psutil包来实现对"以太网"和"WLAN"的监控,包含以下3个基本功能:
  1. 单独开一个进程进行网速监控
  2. 将网速信息写入日志文件
  3. 定期清理日志文件
#!/usr/bin/env python
# coding=utf-8

"""
# :author: Terry Li
# :url: https://blog.csdn.net/qq_42183962
# :copyright: © 2020-present Terry Li
# :motto: I believe that the God rewards the diligent.
"""
————————————————
版权声明:本文为CSDN博主「木法星人」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_42183962/article/details/114323336

from os import getcwd
from multiprocessing import Process
import psutil, time


class NetWorkCalc:
    def get_net_name(self):
        target_lines = ['以太网', 'WLAN']
        find_turned_on_lines = []
        for net_name, info in psutil.net_if_stats().items(): # snicstats class
            if info.isup == True:
                find_turned_on_lines.append(net_name)
        avaliable_line = list(set(find_turned_on_lines) & set(target_lines))
        # 若网线和WiFi同时连上,Win10系统会优先跑网线
        if '以太网' in avaliable_line:
            return '以太网'
        elif 'WLAN' in avaliable_line:
            return 'WLAN'
        elif len(avaliable_line) != 0:
            return 0
        else:
            return -1

    def get_net_io(self, Networked_Line, Step_Time=1.0):
        before_io = psutil.net_io_counters(pernic=True)[Networked_Line].bytes_recv
        time.sleep(Step_Time)
        after_io = psutil.net_io_counters(pernic=True)[Networked_Line].bytes_recv
        speed = (after_io - before_io)/1024
        return "%.2f K/s" % speed
        
    def check(self,Step_Time=1.0):
        net_name = self.get_net_name()
        if isinstance(net_name, str):
            # print(psutil.net_io_counters(pernic=True)[net_name]) # snetio class
            return self.get_net_io(Networked_Line=net_name, Step_Time=Step_Time), True
        else:
            time.sleep(Step_Time)
            if net_name == -1:
                return "Error, No available Network card detected.", False
            elif net_name == 0:
                return "Error, Check whether '以太网' or 'WLAN' are Turned ON.", False
            else:
                return "Unknown Error.", False


class Monitor(Process):
    def __init__(self, name):
        super().__init__()
        self.name = name
        
    def run(self):
        self.loops_work()
        
    def loops_work(self):
        nwc = NetWorkCalc()
        get_now_timestamp = lambda:int(time.time())
        start_time = get_now_timestamp()
        run_times =  7 * 86400
        log_path = getcwd() + '/monitor_network_log.txt'
        while 1:
            now_time = get_now_timestamp()
            if (now_time -  start_time) % run_times == 0:
                # 清空日志文件
                with open(log_path, 'w', encoding='utf8') as f:
                    f.write('')
            else:
                with open(log_path, 'a', encoding='utf8') as f:
                    result = nwc.check()
                    # print(str(result))
                    f.write(time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(now_time)) + str(result) + '\n')



if __name__ == "__main__":
    
    # os = platform.system()
    m = Monitor(name='NetWorkMonitorTools')
    m.start()
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木法星人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值