0

I have a little complex code developed using Python 3.8.10 for image processing. This code is interfaced with C# GUI using "Process()" method.

The code is working but the issue is that all my status updates (print statements) in Python do not show up until the end of the code.

For example in python_code.py,

print(f"Loading model {model_name}, please wait......"
......
......
print(f"Inference completed, loading next image, ......")
......
......

C# code is as follows :

public void AI_SJV_run(string ImageFile, RawBGAXrayParameterFiles AI_Recipe)
{
    // https://medium.com/emoney-engineering/running-python-script-from-c-and-working-with-the-results-843e68d230e5
    // https://www.tensorflow.org/hub/tutorials/image_retraining
    MessageEventArgs e = new MessageEventArgs();
    e.message = @"<<<<<<< Script initiaited, please wati.... >>>>>>>";
    ProcessStartInfo start = new ProcessStartInfo();
    Process process = new Process();
    //start.FileName = (Params.Xray_file.DetectionParameters.Algorythm == SJWalgorythm.CONTOUR) ? ContourPython : CirclePython;
    //string pythonFile = string.Format("{0}\\{1}.py", PythonAlgorythmFolder, AI_Recipe.Xray_file.DetectionParameters.PythonAlgorythm);
    string pythonFile = SJV_Inference_code;
    // if (File.Exists(pythonFile))
    start.FileName = pythonEXEPath;
    if (File.Exists(pythonFile))
    {
        if (File.Exists(start.FileName))
        {
            string pythonParams = "";
            // AI_Recipe.Xray_file.DetectionParameters.imageParameters is empty for AI recipe
            string ParameterName = AI_Recipe.Xray_file.DetectionParameters.PythonAlgorythm; 

            pythonParams = pythonParams + string.Format("{0} \"{1}\" ", "--AI_Recipe", ParameterName);

            string arg = String.Format("--ImageFolder \"{0}\" {1}", ImageFile, pythonParams);

            start.Arguments = string.Format("\"{0}\" {1}", pythonFile, arg);

            log.Write("Python file : " + start.FileName + "Python parameters >>> " + start.Arguments);

            m.message = start.Arguments;
            sendPythonMessage(this, m);
            sendPythonMessage(this, e);

            start.UseShellExecute = false;
            start.CreateNoWindow = true;
            start.RedirectStandardOutput = !start.UseShellExecute;
            start.RedirectStandardError = !start.UseShellExecute;

            process.StartInfo = start;

            process.EnableRaisingEvents = true;
            process.OutputDataReceived += SJW_Output;
            process.ErrorDataReceived += SJW_Error;
            process.Exited += new EventHandler(SJW_Exited);

            process.Start();

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();
        }
        else
        {
            m.message = "Python executable not found : " + start.FileName;
            sendPythonMessage(this, m);
        }
    }
    else
    {
        m.message = "Algorythm file not found : " + pythonFile;
        sendPythonMessage(this, m);
    }
}
public void AI_SJV_Output(object sender, DataReceivedEventArgs e)
{
    try
    {
        string results = e.Data;
        if (results != null)
        {
            m.message = results;
        }
    }
    catch (Exception ex)
    {
        m.message = "ERROR @ SJW_Output : " + ex.Message + "EXCEMPTION : " + ex.InnerException;
    }
    sendPythonMessage(this, m);
}
private void AI_SJV_Error(object sender, DataReceivedEventArgs e)
{
    string ErrorResult = e.Data;
    if (ErrorResult != null)
    {
        try
        {
            m.message = "SJW Error :" + ErrorResult;
        }
        catch (Exception ex)
        {
            m.message = "ERROR @ SJW_Error : " + ErrorResult + "  " + ex.Message + "EXCEMPTION : " + ex.InnerException;
        }
        sendPythonMessage(this, m);
    }
}
private void AI_SJV_Exited(object sender, EventArgs e)
{
    Bumps bumps = new Bumps();
    try
    {
        m.message = "<<<<<<< Script completed >>>>>>>";
    }
    catch (Exception ex)
    {
        m.message = "ERROR @ SJQ_Exited : " + ex.Message + "EXCEMPTION : " + ex.InnerException;
    }
    sendPythonMessage(this, m);
}

print statements in Python do not trigger "AI_SJV_Output" method until end of the code But at the end, it dumps all statements ran until then.

Any help?

PCG
  • 2,049
  • 5
  • 24
  • 42
  • `sys.stdout` which `print` uses by default is buffered... you can either add an explicit `flush=True` to your print or unbuffer stdout... does that work? – Jon Clements Jul 09 '22 at 18:28
  • I suspect https://stackoverflow.com/questions/107705/disable-output-buffering will be of use here but I don't have C# handy to test your specific case – Jon Clements Jul 09 '22 at 18:29
  • @JonClements, I already tried that method (sys.stdout.flush()), no change. But if I open the shell by "start.UseShellExecute = true;" I see all updates in real time. – PCG Jul 09 '22 at 18:37

0 Answers0