如何为路由器测速脚本实现实时进度条追踪函数执行
实现真实实时的测速进度条方案
我明白你的痛点——用tqdm结合预设sleep的方式完全是假进度,根本没法真实反映测速的实际耗时。要实现真实追踪10秒测速过程的进度条,我们可以用后台线程+实时时间计算的方案,让进度条和测速任务并行运行,完全不会增加总耗时。
核心思路
- 启动一个后台线程专门负责更新进度条,它会实时计算从测速开始到当前的时间,以此算出真实进度。
- 主线程专注执行你的测速函数(下载/上传),两者并行不干扰。
- 进度条用
\r实现单行刷新,确保输出整洁,符合你想要的download testing [---------->]100%样式。
完整代码示例
import threading import time import sys # 替换成你自己的下载测速函数(确保它会运行约10秒) def download_speed_test(): # 这里模拟你的下载测速逻辑,比如调用测速API/执行测速命令 time.sleep(10) # 仅作示例,替换为真实测速代码 # 替换成你自己的上传测速函数 def upload_speed_test(): time.sleep(10) # 仅作示例,替换为真实测速代码 def show_progress(total_duration, task_label, stop_signal): start_time = time.time() bar_length = 10 # 进度条的字符长度,可调整 while not stop_signal.is_set(): elapsed_time = time.time() - start_time # 计算当前进度,超过总时长则直接设为100% progress = min((elapsed_time / total_duration) * 100, 100) filled_bars = int(bar_length * progress // 100) # 构建进度条样式:已完成部分用=,当前位置用>,未完成用- if filled_bars >= bar_length: bar = "=" * bar_length else: bar = "=" * filled_bars + ">" + "-" * (bar_length - filled_bars - 1) # 单行刷新输出进度 sys.stdout.write(f"\r{task_label} [{bar}] {int(progress)}%") sys.stdout.flush() # 如果进度已经到100%,主动停止线程 if progress >= 100: stop_signal.set() time.sleep(0.1) # 每0.1秒更新一次,平衡流畅度和性能 def main(): # 执行下载测速+进度条 download_stop = threading.Event() progress_thread = threading.Thread( target=show_progress, args=(10, "download testing", download_stop) ) progress_thread.start() # 运行真实的下载测速函数 download_speed_test() # 通知进度条线程停止,并等待它结束 download_stop.set() progress_thread.join() print() # 换行,准备下一个进度条 # 执行上传测速+进度条,逻辑和下载一致 upload_stop = threading.Event() progress_thread = threading.Thread( target=show_progress, args=(10, "upload testing", upload_stop) ) progress_thread.start() upload_speed_test() upload_stop.set() progress_thread.join() print() # 最终换行 # 输出测速结果 print("测速完成!") # 这里可以添加你的结果输出逻辑,比如打印下载/上传速度 if __name__ == "__main__": main()
关键细节说明
- 线程并行:进度条线程和测速线程同时运行,完全不会增加测速的总耗时,进度是基于测速的真实运行时间计算的。
- 停止信号:用
threading.Event()来控制进度条线程的结束,不管测速是按时完成还是提前结束,进度条都会立刻停止并显示100%。 - 自定义样式:你可以调整
bar_length来改变进度条的长度,或者修改=、>、-这些字符来自定义进度条的外观。 - 真实进度:进度条的每一次更新都是基于当前已流逝的时间和预设的10秒总时长计算,完全符合你要的“最后一秒显示90%左右”的真实效果。
把你现有的download_speed_test和upload_speed_test函数替换掉示例里的模拟代码,就能直接用啦!
内容的提问来源于stack exchange,提问作者Blackhat
相关产品推荐
相关产品推荐

