Python Popen在线程中写入stdin无效

4 投票
2 回答
3812 浏览
提问于 2025-04-16 19:35

我正在尝试写一个程序,想要同时读取和写入一个进程的标准输出和标准输入。不过,似乎在一个线程中写入程序的标准输入并不奏效。以下是相关的代码片段:

import subprocess, threading, queue

def intoP(proc, que):
    while True:
        if proc.returncode is not None:
            break
        text = que.get().encode() + b"\n"
        print(repr(text))      # This works
        proc.stdin.write(text) # This doesn't.


que = queue.Queue(-1)

proc = subprocess.Popen(["cat"], stdin=subprocess.PIPE)

threading.Thread(target=intoP, args=(proc, que)).start()

que.put("Hello, world!")

出什么问题了?有没有办法解决这个问题?

我在Mac OSX上运行的是python 3.1.2,确认在python 2.7中是可以正常工作的。

2 个回答

0

我把proc.stdin.write(text)改成了proc.communicate(text),这样在Python 3.1中就能正常工作了。

8

答案是 - 缓冲。 如果你在

proc.stdin.flush()

这个代码行后面加上一个东西,调用proc.stdin.write()之后,你就会看到“Hello, world!”被打印到控制台上(由子进程打印),这正是你所期待的结果。

撰写回答