gpt4 book ai didi

Python Popen 写入 stdin 在线程中时不起作用

转载 作者:太空狗 更新时间:2023-10-30 02:34:46 26 4
gpt4 key购买 nike

我正在尝试编写一个程序,分别同时读取和写入进程的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com