我运行了一个命令行程序,可以接受任何以stdin中的“Enter”键结束的文本输入,并立即向stdout发送文本响应 . 现在我有一个包含数千个句子和每行一个句子的文件 . 我可以使用两个线程,一个用于逐行读取此文件并在运行命令行程序时将其发送到stdin,另一个线程用于捕获响应并写入另一个文件?

对于“发送到stdin”线程:

def readSentence(inpipe, senlines):
    for sen in senlines:
        inpipe.write(sen.strip()+'\n')
    inpipe.close()

对于“从stdout获取”主题:

def queueResult(outpipe, queue):
    for res in iter(outpipe.readlines()):
        queue.put(res)
    outpipe.close()

调用命令行程序的主线程:

def testSubprocess():
    ee = open('sentences.txt', 'r')
    ff = open('result.txt', 'w')
    lines = ee.readlines()
    cmd = ['java', 
           '-cp', 'someUsefulTools.jar', 
           'fooClassThatReadSentenceAndOutputResponse', 
           '-stdin',]   # take input from stdin
    proc = Popen(cmd, stdout=PIPE, stdin=PIPE)
    q = Queue()
    readThread = Thread(target=readSentence, args=(proc.stdin, lines))
    queueThread = Thread(target=queueResult, args=(proc.stdout, q))
    readThread.daemon = True
    queueThread.daemon = True
    readThread.start()
    queueThread.start()

    result = []

    try:
        while not q.empty(): 
            result = result.append(q.get_nowait())
    except Empty:
        print 'No results!'

我在readSentence()和queueResult()中的for循环中打印输入和输出(上面的代码中没有显示) . 我最后发现输入句子没有被完全读出,输出也没什么 . 我的代码可能出现什么问题?如何实现“stdin”-thread和“stdout”-thread之间的同步,以便它们可以成对工作?即“stdin”-thread将一个句子放入管道,然后“stdout”-thread从管道中获取结果 .

附:我引用这篇文章进行非阻塞读取:Non-blocking read on a subprocess.PIPE in python