Files
FACULTATE-HEALTHCARE_MANAGER/backend/Application/Endpoints/SicknessPrediction/PythonScriptRunner.cs
T
2024-04-12 12:25:08 +03:00

55 lines
1.9 KiB
C#

using System.Diagnostics;
namespace Application.Endpoints.SicknessPrediction;
public class PythonScriptRunner
{
public async Task<BaseResponse> 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;
}
}
}