0

I have a C# GUI from which I run a python script that takes about 2 minutes. Rather than direct the output of the Python script to a file, I'd like to have GUI show all the print-outs that the Python script makes, say, in a text box, as the process is running. Any solution I've found typically waits for the process to end before redirecting the standard output to the text box, and I'm not sure if I'm searching for a solution correctly. Does anyone have an idea about how to do this? Here's some code for reference:

using (Process proc = new Process())
{

    debug_output.AppendText("All debug output will be listed below\n");
    string pyFileName = "hello.py";
    string args = "arg1";
    proc.StartInfo.FileName = "C:\\Python27\\python.exe";
    proc.StartInfo.Arguments = string.Format("{0} {1}", pyFileName, args);
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.OutputDataReceived += new DataReceivedEventHandler(MyProcOutputHandler);
    proc.Start();

    proc.BeginOutputReadLine();
    while (!proc.HasExited)
    {
        Application.DoEvents();
    }
}

With The following Handler:

private void MyProcOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    if (!String.IsNullOrEmpty(outLine.Data))
    {
        if (debug_output.InvokeRequired)
        {
            debug_output.BeginInvoke(new DataReceivedEventHandler(MyProcOutputHandler), new[] { sendingProcess, outLine });
        }
        else
        {
            debug_output.AppendText(outLine.Data);
            debug_output.AppendText("\n");
        }       
    }
    Console.WriteLine(outLine.Data);
}

As an update, I tried the solution from this post since it looks like the exact same problem, but I still don't get it working. My output ends up in the right place, but only after the whole script is done running. Please help.

Community
  • 1
  • 1
amanama93
  • 77
  • 1
  • 6
  • 1
    possible duplicate of [C# get process output while running](http://stackoverflow.com/questions/11994610/c-sharp-get-process-output-while-running) – hlt Aug 11 '14 at 18:19
  • I have tried the suggestions from this post and they haven't worked, the handler doesn't get called until after the process has exited. – amanama93 Aug 12 '14 at 18:14

0 Answers0