开发者

How do I wrap an REPL using .NET?

开发者 https://www.devze.com 2023-01-10 21:27 出处:网络
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 usi

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 = ProcessStartInf开发者_Go百科o()
    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").


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消