多次发送和接收数据以进行子处理(Python)

时间:2019-04-05 08:19:52

标签: python python-3.x windows subprocess

问题

我正在与终端应用程序(xfoil)通信,我想隔离与每个stdin对应的stdout。 这个问题也比较笼统,因为我想知道为什么我无法使用子进程打开应用程序,然后依次使用其stdin和stdout(或者我该怎么做)。

我现在能做什么

到目前为止,我可以使用process.communicate发送指令到Xfoil,该指令将检索整个标准输出。

import subprocess
xfoil = subprocess.Popen('path_to_xfoil.exe', stdin=subprocess.PIPE, \
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
[output, _] = xfoil.communicate(input=instructions)

我要实现的目标

我不必处理整个标准输出,而是希望隔离每组指令(stdin)和结果(stdout)。 符合以下条件的

output1 = process.communicate(input=instructions1)
output2 = process.communicate(input=instructions2)
output3 = process.communicate(input=instructions3)
...

我需要使流程保持开放状态(通信情况并非如此)。

我尝试过的事情

Communicate multiple times with a process without breaking the pipe?可能是解决问题的方法,但是它没有清楚说明如何读取输出,下面的代码只是冻结了,可能是因为我不知道何时停止读取。

xfoil.stdin.write(instructions1)
xfoil.stdout.read()  # never passes this line
xfoil.stdin.write(instructions2)
xfoil.stdout.read()

Non-blocking read on a subprocess.PIPE in python似乎也是一条不错的路,但是它只负责输出。

或者也许我需要像ipc - communicate multiple times with a subprocess in Python中那样使用os模块?

谢谢您的帮助

PS:我读了一点关于fcntl的内容,但是我需要使代码在Linux和Windows上都能工作。

0 个答案:

没有答案