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

如何保持os.system启动的CMD窗口持续打开?

问题描述

在Windows设备上使用Python脚本自动化流程时遇到异常:通过os.system启动CMD窗口执行adb shell中的iperf命令,功能可正常启动,但窗口会随机无规律自行关闭。

  • 移动端直接使用iperf应用可持续运行数日,即便网络出现问题也不会中断;
  • 脚本使用完全相同的参数执行,窗口运行一段时间后就会自动关闭;
  • 已尝试在命令末尾添加&& pause、>output.txt、&& echo a等操作,均未解决问题;
  • 需求:实现窗口仅在手动关闭时才停止运行,和移动端应用表现一致。

原代码:

directory = 'correct_directory'
buildCommand = 'adb'
if Protocol:  #TCP
    if link: #UL
        buildArgs = f'-s {serial_no} shell \"cd data/local/tmp && ./iperf2.1.4 -i2 -c{IP_address} -p{port} -t{str(time_)} \"'
        os.system('cd {} && start "" "{}" {}'.format(directory, buildCommand, buildArgs))
    else: #DL
        buildArgs = f'-s {serial_no} shell \"cd data/local/tmp && ./iperf2.1.4 -s -i2 -p{port} -P 1 \"'
        os.system('cd {} && start "" "{}" {}'.format(directory, buildCommand, buildArgs))
解决思路与方案

问题根源是adb shell在单次命令执行完成(或异常退出)后会自动终止会话,导致CMD窗口随之关闭。要实现持续运行,需让adb shell保持会话不终止,同时守护iperf进程防止意外退出。

关键改动点

  1. 用cmd /k启动窗口:cmd /k参数会让CMD窗口在命令执行后保持打开,不会因adb会话结束而自动关闭;
  2. 添加shell循环守护iperf:在adb交互式shell中用while true循环执行iperf,即使iperf因网络问题退出,也会自动重启,确保会话持续;
  3. 简化命令转义:调整命令拼接逻辑,避免转义符混乱,提升可读性。

修改后的代码

directory = 'correct_directory'
serial_no = 'your_device_serial'  # 替换为你的设备序列号
IP_address = 'your_server_ip'      # 替换为iperf服务器IP
port = 'your_port'                 # 替换为测试端口
time_ = 'your_duration'            # 替换为单次测试时长(如不需要可去掉-t参数)
Protocol = True  # True为TCP,False为UDP
link = True      # True为上传(UL),False为下载(DL)

if Protocol:
    if link:
        # 上传模式:循环执行iperf,异常退出后自动重启
        shell_cmd = f'cd data/local/tmp && while true; do ./iperf2.1.4 -i2 -c{IP_address} -p{port} -t{str(time_)}; sleep 1; done'
        # 启动CMD窗口并保持打开,执行adb交互式shell
        os.system(f'cd {directory} && start cmd /k "adb -s {serial_no} shell \\"{shell_cmd}\\""')
    else:
        # 下载模式:循环启动iperf服务端
        shell_cmd = f'cd data/local/tmp && while true; do ./iperf2.1.4 -s -i2 -p{port} -P 1; sleep 1; done'
        os.system(f'cd {directory} && start cmd /k "adb -s {serial_no} shell \\"{shell_cmd}\\""')

额外说明

  • 如果不需要自动重启iperf,只是想让窗口在iperf结束后保持打开,可将while true循环去掉,改为./iperf2.1.4 ...; exec sh,这样iperf结束后会进入交互式shell,窗口不会关闭;
  • 若要查看输出日志,可在cmd命令中添加重定向,比如start cmd /k "adb ... > iperf_log.txt 2>&1",将输出写入文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:34:58