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")
相关推荐
咩咩啃树皮8 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
灯澜忆梦8 小时前
GO_并发编程---定时器
开发语言·后端·golang
鱟鲥鳚9 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
-银雾鸢尾-9 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-9 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白10 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司11 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地12 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun31415912 小时前
TCP超时重传机制是为了解决什么问题?
java
段一凡-华北理工大学12 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化