Reputation: 31
I wish to embed an exe file (particularly "python.exe", the interpreter of Python 2.7) in my C# Console Application, meaning I want the user to enter commands, receive the interpreter's output into a string variable and use Console.WriteLine to print that output. My code so far is:
ProcessStartInfo processStartInfo = new ProcessStartInfo("C:/Python27/python.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
while (true)
{
process.StandardInput.WriteLine(Console.ReadLine());
process.StandardInput.Close();
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
}
}
I can write "print 5" and get the correct output, but when writing it again I get the following error:
Cannot write to a closed TextWriter.
I believe this error is because I close the StandardInput, but without that line of code I don't get any output at all. What can I use to send multiple commands to the exe?
Thank you in advance!
Upvotes: 3
Views: 487
Reputation: 4559
Call process.StandardInput.Flush()
instead. Flush makes any buffered TextWriter write all of its input to the destination, which is what's happening here - you're calling Close()
which has the side effect of flushing the buffers as well as closing the stream.
See the MSDN documentation for more info.
Upvotes: 1