subprocess Popen stdin 只会在脚本完成后输入和 运行

subprocess Popen stdin will only input and run after the script has finished

描述:

我试图制作一个 shell 可以在聊天软件上进行交互,所以我需要一个 cmd.exe 作为子进程并将字符串传递到进程中。

我有这个:

from subprocess import Popen
from subprocess import PIPE as p

proc = Popen("cmd",stdout=p,stdin=p,shell=True)

所以如果我们需要将输入传递给进程,通常我们会使用 proc.stdin.write() 但似乎该字符串只会在python脚本完成

后传入并起作用

例如,我有

#same thing above
proc.stdin.write("ping 127.0.0.1".encode())
time.sleep(10)

脚本将等待 10 秒,然后传递 运行 ping 命令。 这意味着不可能得到结果 stdout.read() 因为什么都没有。

我曾尝试使用 subprocess.Popen.communicate() 但它会在一次输入后关闭管道。

有什么方法可以解决 "only run the command after script finish" 的问题,或者让 communicate() 不关闭管道吗?

对管道的写入是缓冲的,您需要刷新缓冲区。

proc.stdin.write("ping 127.0.0.1".encode())
proc.stdin.flush()