Communicate multiple times with a subprocess in Python

时间秒杀一切 提交于 2020-02-05 03:35:30

问题


This question is NOT a duplicate of

Communicate multiple times with a process without breaking the pipe?

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).


Document subprocess.Popen says:

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?

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.


回答1:


Basicly Non-blocking read on a subprocess.PIPE in python

Set the proc pipes (proc.stdout, proc.stdin, ...) to nonblocking mode via fnctl and then write/read them directly.

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




回答2:


This turns out to be not very difficult:

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))


来源:https://stackoverflow.com/questions/39899074/communicate-multiple-times-with-a-subprocess-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!