与Python中的子流程多次通信 [英] Communicate multiple times with a subprocess in Python
问题描述
此问题不是
该问题得以解决,因为其用例允许将输入一起发送,但是如果您的程序是交互式的,则情况并非如此(如此处的用例所示).
That question is solved because its use case allows inputs to be sent together, but this is not true if your program is interactive (as illustrated in the use case here).
文档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. ...
是否可以在子进程终止之前与子进程多次通信,例如与终端或与网络套接字的通信?
Is it possible to communicate multiple times with the subprocess before its termination, like with a terminal or with a network socket?
例如,如果子流程是bc
,则父流程可能希望根据需要向其发送不同的输入以进行计算.由于发送到bc
的输入可能取决于用户输入,因此不可能一次发送所有输入.
For example, if the subprocess is bc
, the parent process may want to send it different inputs for calculation as needed. Since inputs send to bc
may depend on user inputs, it is not possible to send all inputs at once.
推荐答案
基本上通过fnctl
将proc管道(proc.stdout,proc.stdin等)设置为非阻塞模式,然后直接对其进行写入/读取.
Set the proc pipes (proc.stdout, proc.stdin, ...) to nonblocking mode via fnctl
and then write/read them directly.
您可能想使用epoll或通过select
或io
模块进行选择,以提高效率.
You might want to use epoll or select via the select
or io
modules for more efficiency.
这篇关于与Python中的子流程多次通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!