Saving the pipe during the opening process

I have appone that reads in materials from stdinand returns the result after a new linestdout

A simple (silly) example:

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

Opening and closing apprequires a lot of initialization and cleaning (this is the interface to a computer algebraic system), so I want this to be minimal.

I want to open a pipe in Python for this process, write lines to stdinand read the results from stdout. Popen.communicate()does not work for this, as it closes the file descriptor, requiring the channel to reopen.

I tried something like this question: Communicate several times with the process without breaking the phone? but I'm not sure how to wait for the exit. It is also difficult to know a priori how long it will take appto complete input processing, so I don’t want to make any assumptions. I believe that most of my confusion comes from this question: Non-blocking reading on the .PIPE subprocess in python , which states that mixing high and low level functions is not a good idea.

EDIT : Sorry that I did not give any code before, it was interrupted. This is what I have tried so far and it seems to work, I just worry that something went 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                                                                       

Possible problems with this?

+3
source share
2

, . , pexpect. Windows - Windows, winpexpect.

, Python, SAGE. , , , .

+2

, stdin=subprocess.PIPE subprocess.Popen. 'stdin - :

import sys, subprocess

proc = subprocess.Popen(["mathematica <args>"], stdin=subprocess.PIPE, 
                        stdout=sys.stdout, shell=True)
proc.stdin.write("Expand[ (x-1)^2 ]") # Write whatever to the process
proc.stdin.flush()                    # Ensure nothing is left in the buffer
proc.terminate()                      # Kill the process

stdout python. , . http://docs.python.org/library/subprocess.html#popen-objects.

+2

All Articles