如何用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
相关产品推荐
相关产品推荐

