user1785715 user1785715 - 4 months ago 24
Python Question

C# WPF Process getting StandardOutput is intermittent

I have a Python Process running in my C# file for WPF:

ProcessStartInfo StartInfo = new ProcessStartInfo(@"python ", location);
StartInfo.UseShellExecute = false;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.RedirectStandardError = true;
try
{
p.StartInfo = StartInfo;
p.EnableRaisingEvents = true;
p.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
p.Exited += new EventHandler(OnProcessExit);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
catch (Exception exc)
{
Console.Write(exc);
}


and later:

private void OnDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
torOut = e.Data;
Console.WriteLine(torOut);
}
}


My Python program has multiple messages printed a second. When I run this, only some of the output appears; for example,
print "message"
may be called 50 times, and only after the 50th time will all 50 messages appear as a batch.

Is there a problem with my approach, or is the rate at which StandardOutput is read particularly slow / intermittent?

Answer

In case anyone has a similar issue, I eventually solved it. Add the following after any time output is needed:

import sys
sys.stdout.flush()