在 Python 中与子进程多次通信

Communicate multiple times with a subprocess in Python

此问题与

不重复

Communicate multiple times with a process without breaking the pipe?

这个问题已经解决,因为它的用例允许输入一起发送,但如果您的程序是交互式的(如此处的用例所示),则情况并非如此。


文档 subprocess.Popen 说:

communicate(input=None)
    Interact with process: Send data to stdin.  Read data from stdout
    and stderr, until end-of-file is reached.  Wait for process to
    terminate.  ...

是否可以在终止之前与子进程进行多次通信,例如与终端或网络套接字?

例如,如果子进程是bc,父进程可能希望根据需要向其发送不同的输入以进行计算。由于发送到 bc 的输入可能取决于用户输入,因此不可能一次发送所有输入。

基本上Non-blocking read on a subprocess.PIPE in python

通过 fnctl 将 proc 管道(proc.stdout、proc.stdin、...)设置为非阻塞模式,然后直接 write/read 它们。

您可能希望通过 selectio 模块使用 epoll 或 select 以提高效率。

事实证明这并不难:

proc = subprocess.Popen(['bc'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
os.write(proc.stdin.fileno(), b'100+200\n')
print(os.read(proc.stdout.fileno(), 4096))