using System.Diagnostics; namespace Controllers.Processes { public class PyProcess { public static (bool, string) RunPythonProcess(string PyExecutable, string PyScript, bool returns = false, string PyArgs = "") { var start = new ProcessStartInfo { FileName = PyExecutable, Arguments = $"-u {PyScript} {PyArgs}", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; using (Process? process = Process.Start(start)) { // Try to start the process if (process == null) { return (false, "Failed to start the process"); } // Read the stdouts and wait for process to end string result = process.StandardOutput.ReadToEnd(); string errors = process.StandardError.ReadToEnd(); process.WaitForExit(); // If the process Errored if (process.ExitCode != 0) { return (false, $"Python Error : {errors}"); } // If the process is supposed to return if (returns) { string markerStart = "---RESULT_START---"; string markerEnd = "---RESULT_END---"; int startPos = result.IndexOf(markerStart) + markerStart.Length; int endPos = result.IndexOf(markerEnd); if (startPos > -1 && endPos > startPos) { string cleanResult = result.Substring(startPos, endPos - startPos).Trim(); return (true, cleanResult); } } else { return (true, ""); } // Fail Safe return (false, "Result not found"); } } } }