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

如何用Python监控子进程输出并按指定模式终止进程

用subprocess监控子进程并在特定输出时终止

待监控的目标脚本

保存为target_script.py:

import time
for i in range(5):
    print("LOADING " + str(i))
    time.sleep(1)
for i in range(10):
    print("RUNNING " + str(i))
    time.sleep(1)

需求

通过Python 3的subprocess模块启动上述脚本,实时打印其输出,一旦捕获到包含RUNNING的行,立即发送等效于终端CTRL+C的中断信号终止子进程。

实现代码

import subprocess
import sys
import signal

def main():
    # 启动子进程,-u参数关闭输出缓冲,保证实时读取
    proc = subprocess.Popen(
        [sys.executable, "-u", "target_script.py"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True
    )

    try:
        # 逐行读取子进程输出
        for line in iter(proc.stdout.readline, ''):
            line = line.strip()
            print(line)
            # 检测到目标输出,发送中断信号
            if 'RUNNING' in line:
                proc.send_signal(signal.SIGINT)
                print("已发送中断信号,终止子进程")
                break
        # 等待子进程退出,获取状态
        proc.wait()
    except KeyboardInterrupt:
        # 处理主进程被用户中断的情况
        proc.send_signal(signal.SIGINT)
        proc.wait()

if __name__ == "__main__":
    main()

核心要点

  • 禁用输出缓冲:必须加-u参数启动子进程,否则Python会缓冲输出,导致主进程无法实时捕获LOADING和RUNNING的打印内容,这是多数类似方案失效的关键原因。
  • 实时逐行读取:用iter(proc.stdout.readline, '')实现高效的逐行读取,避免阻塞。
  • 发送SIGINT信号:proc.send_signal(signal.SIGINT)完全等效于终端按下CTRL+C,子进程可以正常响应KeyboardInterrupt异常,不会被强制杀死。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:01:02