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")
相关推荐
Ulyanov2 小时前
基于Tkinter/ttk的现代化Python GUI开发全攻略:从布局设计到视觉美化(三)
开发语言·python·gui·tkinter·ttk
等风来Boy2 小时前
JAVA集成CAS客户端总结
java·cas
hutengyi2 小时前
go测试问题记录
开发语言·后端·golang
青槿吖2 小时前
第二篇:Spring Boot进阶:整合异常处理、测试、多环境与日志,开发稳得一批!
java·spring boot·后端·spring·面试·sqlserver·状态模式
星如雨グッ!(๑•̀ㅂ•́)و✧2 小时前
Spring WebFlux 中的并发
java·spring·oracle
weixin_433179332 小时前
python - 读写文件
开发语言·python
東雪木2 小时前
java学习—— 8 种基本数据类型 vs 包装类、自动装箱 / 拆箱底层原理
java·开发语言·java面试
Lyyaoo.2 小时前
【JAVA基础面经】JVM、JRE、JDK
java·开发语言·jvm
liulilittle2 小时前
SQLite3增删改查(C
c语言·开发语言·数据库·c++·sqlite