I want to run my long runing python script from my console app.
I use
("my_script.py"), when I shut down console also python script is terminate.
In task manager all(console app and script) is runing under .Net Core Host.
How to run python as completly separated process?
Normally, this would start your python script completely outside of your console application:
System.Diagnostics.Process.Start(@"C:\path\to\my_script.py");
In classic .NET it will invoke the process via a new shell, but in .NET Core, the process is created directly inside the existing executable. There is an option to change this, called UseShellExecute. This is directly from the Microsoft documentation:
trueif the shell should be used when starting the process;falseif the process should be created directly from the executable file. The default istrueon .NET Framework apps andfalseon .NET Core apps.
This is how you can use it:
var myPythonScript = new Process();
myPythonScript.StartInfo.FileName = @"C:\path\to\my_script.py";
myPythonScript.StartInfo.UseShellExecute = true;
myPythonScript.Start();
When your C# console app terminates, your python script should still be running.
Thanks to Panagiotis Kanavos, he made me realize the UseShellExecute has nothing to do with the parent/child relationship between the processes. So I setup a sandbox locally with .NET Core and played around with it a bit and this is working for me:
var myPythonScript = new Process();
myPythonScript.StartInfo.FileName = @"C:\path\to\python.exe"; // the actual python installation executable on the server
myPythonScript.StartInfo.Arguments = @"""C:\path\to\my_script.py""";
myPythonScript.StartInfo.CreateNoWindow = true;
myPythonScript.Start();
When the parent app terminates, my python script is still running in the background.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With