subprocess与子进程交互

1.readline存在阻塞机制,启动线程监控

2.检测到exit、quit,终止process子进程-》终止进程完成会关闭stdout、stderr-》关闭后pipe.readline返回''-》子线程跳出循环结束

python 复制代码
import subprocess
import threading
import time


def read_output(pipe):
    try:
        for line in iter(pipe.readline, ''):
            if not line:
                break
            print(line, end='')
    finally:
        pipe.close()

process = subprocess.Popen(
    ["python","-i"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    bufsize=1
)

# 启动线程
threads = [
    threading.Thread(target=read_output, args=(process.stdout,)),
    threading.Thread(target=read_output, args=(process.stderr,))
]

for t in threads:
    t.start()

try:
    while True:
        cmd = input(">>> ")
        if cmd.strip().lower() in ("exit", "quit"):
            break
        process.stdin.write(cmd + "\n")
        process.stdin.flush()
        time.sleep(0.001)

except KeyboardInterrupt:
    print("Interrupted")

finally:
    process.terminate()

    try:
        process.wait(timeout=5)
    except subprocess.TimeoutExpired:
        process.kill()

    # 关闭 stdin
    if process.stdin:
        process.stdin.close()

    # 等线程退出
    for t in threads:
        t.join(timeout=2)

    print("Process closed")
相关推荐
雪的季节11 分钟前
RabbitMQ详解
开发语言
小bo波40 分钟前
枚举实战
java·设计模式·枚举·后端开发·代码重构
ice8130331811 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
夜微凉41 小时前
三、Spring
java·后端·spring
三品吉他手会点灯1 小时前
C语言学习笔记 - 44.运算符和表达式 - 运算符2 - 除法与取余运算符
c语言·开发语言·笔记·算法
kkeeper~1 小时前
0基础C语言积跬步之动态内存管理
c语言·开发语言
橘右今1 小时前
2026 Java后端高频面试宝典
java·开发语言·面试
J-Tony111 小时前
【JVM】根可达算法
jvm·算法
微小冷2 小时前
Julia卫星工具箱SatelliteToolbox简介
开发语言·航天·坐标转换·julia·卫星工具箱
2601_colin2 小时前
Codex插件全流程实战指南
开发语言·经验分享·笔记·微信开放平台