using System.Diagnostics; namespace Application.Endpoints.SicknessPrediction; public class PythonScriptRunner { public async Task RunPythonScript(string scriptPath, string args) { var response = new BaseResponse(); using (Process process = new Process()) { process.StartInfo = new ProcessStartInfo("python", $"\"{scriptPath}\" \"{args}\"") { RedirectStandardOutput = true, RedirectStandardError = true, // Redirect standard error to capture any errors. UseShellExecute = false, CreateNoWindow = true, }; try { process.Start(); // Read output and error streams. var output = await process.StandardOutput.ReadToEndAsync(); var error = await process.StandardError.ReadToEndAsync(); process.WaitForExit(); if (process.ExitCode == 0) // Assuming exit code 0 as a success. { Console.WriteLine(output); response.StatusCode = HttpStatusCodes.OK; response.Message = "Success"; response.Data = output; } else { Console.WriteLine(error); response.StatusCode = HttpStatusCodes.InternalServerError; response.Message = error; // Using the error output as the message if not successful. response.Data = null; } } catch (Exception ex) { response.StatusCode = HttpStatusCodes.InternalServerError; response.Message = $"An error occurred while executing the Python script: {ex.Message}"; response.Data = null; } return response; } } }