与Python中的子流程多次通信 [英] Communicate multiple times with a subprocess in Python

查看:76
本文介绍了与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或通过selectio模块进行选择,以提高效率.

You might want to use epoll or select via the select or io modules for more efficiency.

这篇关于与Python中的子流程多次通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆