本文介绍了使管道保持打开状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个app,它从stdin中读取内容,并在换行符之后将结果返回到stdout

I have an app that reads in stuff from stdin and returns, after a newline, results to stdout

一个简单的(愚蠢的)示例:

A simple (stupid) example:

$ app
Expand[(x+1)^2]<CR>
x^2 + 2*x + 1
100 - 4<CR>
96

打开和关闭app需要进行大量的初始化和清理工作(它是计算机代数系统的接口),因此我希望将其保持在最低水平.

Opening and closing the app requires a lot of initialization and clean-up (its an interface to a Computer Algebra System), so I want to keep this to a minimum.

我想用Python在此过程中打开一个管道,向其stdin中写入字符串,并从stdout中读出结果. Popen.communicate()对此不起作用,因为它关闭了文件句柄,需要重新打开管道.

I want to open a pipe in Python to this process, write strings to its stdin and read out the results from stdout. Popen.communicate() doesn't work for this, as it closes the file handle, requiring to reopen the pipe.

我已经尝试了一些与此相关问题类似的方法:与一个进程多次通信而不破坏管道?,但我不确定如何等待输出.很难先验地知道app需要多长时间才能处理完手头的输入,因此我不想做任何假设.我想我的大部分困惑都来自以下问题: Non-blocking在subprocess.PIPE中的python上阅读,其中指出混合高级函数和低级函数不是一个好主意.

I've tried something along the lines of this related question:Communicate multiple times with a process without breaking the pipe? but I'm not sure how to wait for the output. It is also difficult to know a priori how long it will take the app to finish to process for the input at hand, so I don't want to make any assumptions. I guess most of my confusion comes from this question: Non-blocking read on a subprocess.PIPE in python where it is stated that mixing high and low level functions is not a good idea.

编辑:抱歉,我之前没有提供任何代码,被打断了.到目前为止,这是我已经尝试过的方法,并且似乎可以正常工作,我只是担心某些错误会被忽略:

EDIT:Sorry that I didn't give any code before, got interrupted. This is what I've tried so far and it seems to work, I'm just worried that something goes wrong unnoticed:

from subprocess import Popen, PIPE
pipe = Popen(["MathPipe"], stdin=PIPE, stdout=PIPE)
expressions = ["Expand[(x+1)^2]", "Integrate[Sin[x], {x,0,2*Pi}]"] # ...
for expr in expressions:
    pipe.stdin.write(expr)
    while True:
        line = pipe.stdout.readline()
        if line != '':
            print line
        # output of MathPipe is always terminated by ';'
        if ";" in line:
            break

潜在的问题吗?

推荐答案

使用子流程,您不能可靠地做到这一点.您可能想看看使用 pexpect 库.在Windows上将无法使用-如果您在Windows上,请尝试 winpexpect .

Using subprocess, you can't do this reliably. You might want to look at using the pexpect library. That won't work on Windows - if you're on Windows, try winpexpect.

此外,如果您尝试使用Python进行数学运算,请查看 SAGE .他们在与其他开源数学软件进行接口方面做了大量工作,因此他们很有可能已经完成了您要尝试的工作.

Also, if you're trying to do mathematical stuff in Python, check out SAGE. They do a lot of work on interfacing with other open-source maths software, so there's a chance they've already done what you're trying to.

这篇关于使管道保持打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:14