views:

36

answers:

1

I'm trying to make a .NET wrapper for an REPL (specifically Scheme, but I haven't got to where it matters). I looked for some sort of expect-style library, but I couldn't find one, so I've been using a System.Diagnostics.Process. I don't think I'm succeeding at reading and writing correctly.

Here's my code; it's in IronPython, but I had similar results in C#:

from System.Diagnostics import *

def get_process(cmd):
    psi = ProcessStartInfo()
    psi.RedirectStandardOutput = True
    psi.RedirectStandardInput = True
    psi.RedirectStandardError = True
    psi.UseShellExecute = False
    psi.FileName = cmd

    prc = Process()
    prc.StartInfo = psi

    return prc

def read_to_prompt(prc):
    output = ""
    while prc.StandardOutput.Peek() > 0:
        output += chr(prc.StandardOutput.Read())
    return output

prc = get_process("racket.exe")
prc.Start()

print read_to_prompt(prc)

prc.StandardInput.WriteLine("(+ 3 15)\n")
prc.StandardInput.Flush()

print read_to_prompt(prc)

prc.Kill()

And here is the output:

Welcome to Racket v5.0.1



C:\home>

I'd expect it to eventually allow me to read the prompt (something like "> "), and the result of the expression I entered ("(+ 3 15)" should return "18").

+2  A: 

I found the answer: I needed to insert

prc.StandardOutput.DiscardBufferedData()

before I try reading again. A StreamReader will often buffer more data than you read, and if the stream is changed, it won't necessarily know.

JasonFruit