0

I want to have results in real time of exections python script via cmd.

My C# code with start pyhton script:

 static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
    {
       // Console.WriteLine("Output from other process");
        Console.WriteLine(e.Data);
    }

    static void cmd_Error(object sender, DataReceivedEventArgs e)
    {
       // Console.WriteLine("Error from other process");
        Console.WriteLine(e.Data);
    }
  private void backgroundWorker_sizzer_DoWork(object sender, DoWorkEventArgs e)
        {
            ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
            cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
            cmdStartInfo.RedirectStandardOutput = true;
            cmdStartInfo.RedirectStandardError = true;
            cmdStartInfo.RedirectStandardInput = true;
            cmdStartInfo.UseShellExecute = false;
            cmdStartInfo.CreateNoWindow = true;

            Process cmdProcess = new Process();
            cmdProcess.StartInfo = cmdStartInfo;
            cmdProcess.ErrorDataReceived += cmd_Error;
            cmdProcess.OutputDataReceived += cmd_DataReceived;
            cmdProcess.EnableRaisingEvents = true;
            cmdProcess.Start();
            cmdProcess.BeginOutputReadLine();
            cmdProcess.BeginErrorReadLine();

            cmdProcess.StandardInput.WriteLine("cd C:\\Users\\");     
            cmdProcess.StandardInput.WriteLine("py test.py");     //Execute script
            cmdProcess.StandardInput.WriteLine("exit");                  //Execute exit.

            cmdProcess.WaitForExit();
        }

test.py file containt simple example:

import time

time.sleep(5) # Sleep for 5 seconds
print("hello")
time.sleep(10) # Sleep for 10 seconds
print("hello")
time.sleep(15) # Sleep for 15 seconds
print("hello")
time.sleep(1) # Sleep for 1 seconds

And now when I run backgroundworker it display all hello at once - when python scripts end his execution.

All I want is display hello in real time one by one. When I start it via cmd manually it works good and show "hello" one by one in real time.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Adamszsz
  • 561
  • 3
  • 13

1 Answers1

2

The issue has to do with buffering the IO in python, since you're calling a process in C# and waiting for it to finish before reading the output buffer.

Try to flush the buffer in your python code after each print using this:

sys.stdout.flush()
Majd Odeh
  • 181
  • 1
  • 11