繁体   English   中英

Python 在线程中打开写入标准输入时不起作用

[英]Python Popen writing to stdin not working when in a thread

我正在尝试编写一个程序,该程序分别同时读取和写入进程的 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”打印到控制台(由子进程)。 如您所料。

我将 proc.stdin.write(text) 更改为 proc.communicate(text),这适用于 Python 3.1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM