I want my C# (.NET 8) app to start a Python script under Python 3.12. The Python script is fairly resource-intensive. When I run the script manually, all is well; it consumes memory up to a bit over 3 GB RAM, then completes. But when I run it in C# by spawning a new CMD window, it consumes just about 1 GB of memory and then the process CPU drops to 0% and it hangs indefinitely.
This is the code I’m using to first activate the virtual environment, then run the script and capture its output.
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd",
Arguments = "",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WorkingDirectory = workingDirectory
}
};
process.StartInfo.EnvironmentVariables.Add("TRANSFORMERS_CACHE", _transformersCacheDirectory);
process.Start();
using var sw = process.StandardInput;
if (sw.BaseStream.CanWrite)
{
sw.WriteLine(".\venv\scripts\activate");
sw.WriteLine($"python test.py");
sw.Flush();
sw.Close();
}
result = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
var error = await process.StandardError.ReadToEndAsync();
2