I am trying to activate a python project env from C# windows console application/ windows service. But system cannot read activate file. How to activate my python project env from C#?
Here is my code-
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"\AppData\Local\Programs\Python\Python37\python.exe";
start.WorkingDirectory = "path to my python project";
start.Arguments = ".\\env\\Scripts\\activate && python manage.py runserver";// "env/Scripts/activate.bat && python manage.py runserver";// "E:\\Blockchain\\25.05.2022_Service\\backend\\env\\Scripts\\activate";// && E:\\Blockchain\\07.04.2022 bat file\\First Part\\Authentication\backend & python manage.py runserver
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Finally I got a solution. Here is my complete code for running python django server from C#
var process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
// directory of project where env folder is exist.
process.StartInfo.WorkingDirectory = workingDirectory;
process.Start();
/* runServerCommand is for the script to run.
In my case it was- "env\\Scripts\\activate && python manage.py runserver" */
process.StandardInput.WriteLine(runServerCommand);
process.StandardInput.Flush();
process.StandardInput.Close();
using (var reader = process.StandardOutput)
{
var result = reader.ReadToEnd();
Console.Write(result);
}