Reputation: 13
I would like to write a C# application that interacts with a python process. See sample code below. After starting the python process and writing to its StdIn, nothing happens until the StdIn stream is closed. When closed, the code submitted via StdIn is executed then the python process closes. How can I get python to execute the code submitted via StdIn without having to first close the StdIn?
StringBuilder strOut = new StringBuilder();
ProcessStartInfo processStartInfo = new ProcessStartInfo();
Process process = new Process();
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;
processStartInfo.Arguments = "";
processStartInfo.FileName = "c:\\Python39\\python.exe";
process.StartInfo = processStartInfo;
process.EnableRaisingEvents = true;
process.OutputDataReceived += new DataReceivedEventHandler
(
delegate (object sndr, DataReceivedEventArgs ee)
{
Console.WriteLine("received=" + ee.Data);
strOut.Append(ee.Data);
}
);
process.ErrorDataReceived += new DataReceivedEventHandler
(
delegate (object sndr, DataReceivedEventArgs ee)
{
Console.WriteLine("error=" + ee.Data);
strOut.Append("Error:" + ee.Data);
}
);
process.Start();
StreamWriter wrtr = process.StandardInput;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
wrtr.WriteLine("import sys");
wrtr.WriteLine("print('Line 1')");
Thread.Sleep(1000);
wrtr.WriteLine("prxint('Line 2')");
wrtr.WriteLine("sys.exit('Test Exit')");
wrtr.Close();
Thread.Sleep(1000);
process.WaitForExit();
process.CancelOutputRead();
string output = strOut.ToString();
Upvotes: 1
Views: 285
Reputation: 1427
Python tries to detect what environment it is running under.
It switches to non interactive mode because it is not run in a terminal window due to UseShellExecute = false
. You can enforce interactive mode by passing the -i
argument: processStartInfo.Arguments = "-i";
You can add -q
as well to disable to the copyright and version message
Upvotes: 1