我正在研究一个python程序,它实现了cmd窗口。我正在使用PIPE的子进程。例如,如果我写"dir"(通过stdout),我使用communication()以便从cmd获得响应,它确实有效。
问题是,在while True循环中,这不会工作不止一次,似乎子进程关闭了自己。请帮帮我
import subprocess
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
x=""
while x!="x":
x = raw_input("insert a command n")
process.stdin.write(x+"n")
o,e=process.communicate()
print o
process.stdin.close()
主要问题是,当程序仍在运行但没有从标准输出中读取任何内容时,试图读取subprocess.PIPE
死锁。communicate()
手动终止该进程以停止此操作。
一种解决方案是将读取stdout的代码放在另一个线程中,然后通过Queue访问它,这允许通过超时而不是死锁在线程之间可靠地共享数据。
新线程将连续读取标准,当没有更多数据时停止。
将从队列流中抓取每一行,直到达到超时(队列中没有更多数据),然后将行列表显示在屏幕上。
此过程将适用于非交互式程序
import subprocess
import threading
import Queue
def read_stdout(stdout, queue):
while True:
queue.put(stdout.readline()) #This hangs when there is no IO
process = subprocess.Popen('cmd.exe', shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
q = Queue.Queue()
t = threading.Thread(target=read_stdout, args=(process.stdout, q))
t.daemon = True # t stops when the main thread stops
t.start()
while True:
x = raw_input("insert a command n")
if x == "x":
break
process.stdin.write(x + "n")
o = []
try:
while True:
o.append(q.get(timeout=.1))
except Queue.Empty:
print ''.join(o)