作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试编写一个程序,分别同时读取和写入进程的 std(out/in)。但是,似乎在线程中写入程序的标准输入不起作用。下面是相关的代码:
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,已确认它可以在 python2.7 中运行。
最佳答案
答案是——缓冲。如果你添加一个
proc.stdin.flush()
在 proc.stdin.write()
调用之后,您会看到“Hello, world!”如您所料,打印到控制台(由子进程)。
关于Python Popen 写入 stdin 在线程中时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6351908/
我是一名优秀的程序员,十分优秀!