使用Python监测网络连接和网速

大家好,网络连接和网速在工作中非常重要,本文将介绍如何使用Python程序来监测互联网连接的速度和中断情况。

1.导入所需库文件

首先,需要导入以下库:

python 复制代码
import speedtest
import time
from datetime import datetime

这里选择了第三方库speedtest-cli来执行实际的下载和上传速度测试。

2.创建循环变量

然后,创建一个名为i的变量,并将其值设为True

python 复制代码
i = True

这只是为了在主函数运行时保持循环,只要iTrue,程序就会一直执行下去。

3.执行主要功能的函数

python 复制代码
def run_prog():
    print("Please wait while GPisc runs it's checks...\n")
    try:
        now = datetime.now()
        time_date = now.strftime("%d/%m/%Y %H:%M:%S")
        st = speedtest.Speedtest()
        server = st.get_best_server()
        server_location = server.get("name")
        host = server.get("host")
        dl_speed = st.download()
        ul_speed = st.upload()
        print(f'SERVER: {host} | LOCATION: {server_location}\n')
        with open('DL_LOG.txt', 'a') as log:
            log.writelines(f'{time_date} - DOWNLOAD SPEED: {dl_speed}\n')
        print(f'DOWNLOAD SPEED: {dl_speed}\n')
        with open('UL_LOG.txt', 'a') as log:
            log.writelines(f'{time_date} - UPLOAD SPEED: {ul_speed}\n')
        print(f'UPLOAD SPEED: {ul_speed}\n')
    except:
        with open('NO_NET_LOG.txt', 'a') as log:
            now = datetime.now()
            time_date = now.strftime("%d/%m/%Y %H:%M:%S")
            log.writelines(f'{time_date} - CONNECTION LOST!\n')
            print('CONNECTION LOST!\n')

上述代码是执行所有工作的函数。run_prog函数通过选择测试时的最佳服务器来运行下载和上传速度测试,然后将结果记录在3个.txt文件中 - DL_LOG.txtUL_LOG.txtNO_NET_LOG.txt

4.结果记录和日志

日志中的数据如下所示:

python 复制代码
05/08/2022 23:18:52 - DOWNLOAD SPEED: 51351410.36969972
05/08/2022 23:20:14 - DOWNLOAD SPEED: 54115624.477457255
05/08/2022 23:21:31 - DOWNLOAD SPEED: 50422315.83706379
05/08/2022 23:22:53 - DOWNLOAD SPEED: 48712675.779672034
05/08/2022 23:18:52 - UPLOAD SPEED: 34615688.56533798
05/08/2022 23:20:14 - UPLOAD SPEED: 14661625.766184961
05/08/2022 23:21:31 - UPLOAD SPEED: 36268210.76668299
05/08/2022 23:22:53 - UPLOAD SPEED: 34678387.95052972
25/07/2022 21:17:30 - CONNECTION LOST!
25/07/2022 21:18:30 - CONNECTION LOST!
25/07/2022 21:19:31 - CONNECTION LOST!
25/07/2022 21:20:28 - CONNECTION LOST!

如上所示,这里没有将字节结果转换为Mbps,因为希望结果尽可能准确。如果需要,可以使用hurry.filesize 0.9(https://pypi.org/project/hurry.filesize/)来进行转换。

run_prog函数使用tryexcept来捕获除了速度结果之外的任何内容,这显然是没有连接的情况,因为如果无法连接到速度测试服务器,程序将失败,然后写入无连接日志。

python 复制代码
while i:
    run_prog()
    time.sleep(60)
    print('**********************************************\n')

上述代码执行run_prog函数,然后等待60秒再次运行(这就是为什么创建了i = True)。

程序在每次执行测试时都会在控制台打印输出。

5.主函数循环

以下是完整的脚本:

python 复制代码
import speedtest
import time
from datetime import datetime
i = True
def run_prog():
    print("Please wait while GPisc runs it's checks...\n")
    try:
        now = datetime.now()
        time_date = now.strftime("%d/%m/%Y %H:%M:%S")
        st = speedtest.Speedtest()
        server = st.get_best_server()
        server_location = server.get("name")
        host = server.get("host")
        dl_speed = st.download()
        ul_speed = st.upload()
        print(f'SERVER: {host} | LOCATION: {server_location}\n')
        with open('DL_LOG.txt', 'a') as log:
            log.writelines(f'{time_date} - DOWNLOAD SPEED: {dl_speed}\n')
        print(f'DOWNLOAD SPEED: {dl_speed}\n')
        with open('UL_LOG.txt', 'a') as log:
            log.writelines(f'{time_date} - UPLOAD SPEED: {ul_speed}\n')
        print(f'UPLOAD SPEED: {ul_speed}\n')
    except:
        with open('NO_NET_LOG.txt', 'a') as log:
            now = datetime.now()
            time_date = now.strftime("%d/%m/%Y %H:%M:%S")
            log.writelines(f'{time_date} - CONNECTION LOST!\n')
            print('CONNECTION LOST!\n')
while i:
    run_prog()
    time.sleep(60)
    print('**********************************************\n')
相关推荐
翻滚吧键盘11 分钟前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js
胡耀超18 分钟前
标签体系设计与管理:从理论基础到智能化实践的综合指南
人工智能·python·深度学习·数据挖掘·大模型·用户画像·语义分析
重庆小透明20 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
lang2015092826 分钟前
Reactor操作符的共享与复用
java
秃了也弱了。30 分钟前
Chrome谷歌浏览器插件ModHeader,修改请求头,开发神器
前端·chrome
TTc_36 分钟前
@Transactional事务注解的批量回滚机制
java·事务
博观而约取1 小时前
Django 数据迁移全解析:makemigrations & migrate 常见错误与解决方案
后端·python·django
乆夨(jiuze)1 小时前
记录H5内嵌到flutter App的一个问题,引发后面使用fastClick,引发后面input输入框单击无效问题。。。
前端·javascript·vue.js
忧郁的蛋~1 小时前
HTML表格导出为Excel文件的实现方案
前端·html·excel
小彭努力中1 小时前
141.在 Vue 3 中使用 OpenLayers Link 交互:把地图中心点 / 缩放级别 / 旋转角度实时写进 URL,并同步解析显示
前端·javascript·vue.js·交互