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")