You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CMD中每次将speedtest输出保存为.txt文件及脚本咨询

解决CMD中运行speedtest.exe同时输出到控制台和保存文件的问题

我来帮你搞定这个需求,先看看你原来的脚本里存在的几个关键问题:

  • 文件名里的index变量没被正确解析:原代码中的"out_{index}.txt"不会替换成实际的数字,得用f-string语法才能让变量生效。
  • os.system()拿不到输出内容:它返回的只是命令的退出状态码(0表示成功,非0是错误),不是speedtest.exe打印的测速结果,而且文件对象也没有append()方法,应该用write()。
  • 没捕获命令输出:os.system只会把内容打印到控制台,但没法把输出存到文件里,得用更强大的subprocess模块来实现。
  • 文件资源管理不当:原代码没有正确关闭文件,容易导致资源泄漏,最好用with语句自动管理。

方案1:每次测试生成独立的TXT文件

这个方案会为每次测速生成一个带索引的独立文件(比如out_0.txt、out_1.txt),同时在控制台显示结果:

import subprocess
import time

index = 0

while True:
    # 捕获speedtest的输出,同时支持中文编码
    test_result = subprocess.run(
        ["speedtest.exe"],
        capture_output=True,
        text=True,
        encoding="utf-8"
    )
    
    # 生成带索引的文件名
    log_file_name = f"out_{index}.txt"
    # 用with语句自动管理文件,避免忘记关闭
    with open(log_file_name, "w", encoding="utf-8") as log_file:
        # 写入正常输出
        log_file.write(test_result.stdout)
        # 如果有错误信息,也一并写入
        if test_result.stderr:
            log_file.write("\n--- 错误信息 ---\n")
            log_file.write(test_result.stderr)
    
    # 在控制台打印结果(因为捕获了输出,所以手动打印)
    print(test_result.stdout)
    if test_result.stderr:
        print("\n--- 错误信息 ---")
        print(test_result.stderr)
    
    index += 1
    time.sleep(4)

方案2:所有测试结果追加到同一个日志文件

如果希望把所有测速记录汇总到一个文件里,还可以加上时间戳方便区分:

import subprocess
import time

# 统一的日志文件名
log_file_name = "speedtest_history.txt"

while True:
    test_result = subprocess.run(
        ["speedtest.exe"],
        capture_output=True,
        text=True,
        encoding="utf-8"
    )
    
    # 以追加模式打开文件,每次结果加在末尾
    with open(log_file_name, "a", encoding="utf-8") as log_file:
        # 加上时间戳作为分隔
        log_file.write(f"\n=== 测速时间:{time.strftime('%Y-%m-%d %H:%M:%S')} ===\n")
        log_file.write(test_result.stdout)
        if test_result.stderr:
            log_file.write("\n--- 错误信息 ---\n")
            log_file.write(test_result.stderr)
    
    # 控制台打印带时间戳的结果
    print(f"\n=== 测速时间:{time.strftime('%Y-%m-%d %H:%M:%S')} ===")
    print(test_result.stdout)
    if test_result.stderr:
        print("\n--- 错误信息 ---")
        print(test_result.stderr)
    
    time.sleep(4)

注意事项

  • 确保speedtest.exe在系统的PATH环境变量里,或者把它放在Python脚本的同一目录下;如果不在这两个位置,要写完整路径,比如["C:\\Program Files\\Speedtest\\speedtest.exe"]。
  • 如果测速结果有乱码,可以调整encoding参数为"gbk"(CMD默认编码)试试。

内容的提问来源于stack exchange,提问作者user11766050

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:27:31