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

标签 python multithreading subprocess

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

相关文章:

python - 使用 tkinter 在 python 上显示/更新分数

python - tensorflow 2 keras shuffle每一行梯度问题

c# - 根据 C# 中的条件保护临界区

python - 终止程序退出时在线程中运行的子进程

python - 在subprocess.Popen中,bufsize适用于哪个文件?

python - pip 安装选项 "ignore-installed"和 "force-reinstall"之间的区别

python - 使用Python将Graphml文件导入neo4j并将其导出为CSV

c++ - 有效地从工作线程读取信息

c - 线程结构作为函数参数 C

任务的 Python 并行化(事件循环?)