Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start.Process not run scipt in separate process


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?

like image 673
krkozlow Avatar asked Dec 20 '25 03:12

krkozlow


1 Answers

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:

true if the shell should be used when starting the process; false if the process should be created directly from the executable file. The default is true on .NET Framework apps and false on .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.

EDIT

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.

like image 118
jtate Avatar answered Dec 22 '25 16:12

jtate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!