【发布时间】:2019-03-09 21:58:59
【问题描述】:
我想从我的控制台应用程序运行我长时间运行的 python 脚本。
我用
("my_script.py"),当我关闭控制台时,python 脚本也会终止。
在任务管理器中,所有(控制台应用程序和脚本)都在 .Net Core Host 下运行。
如何将python作为完全分离的进程运行?
【问题讨论】:
我想从我的控制台应用程序运行我长时间运行的 python 脚本。
我用
("my_script.py"),当我关闭控制台时,python 脚本也会终止。
在任务管理器中,所有(控制台应用程序和脚本)都在 .Net Core Host 下运行。
如何将python作为完全分离的进程运行?
【问题讨论】:
通常,这会完全在控制台应用程序之外启动您的 python 脚本:
System.Diagnostics.Process.Start(@"C:\path\to\my_script.py");
在经典 .NET 中,它将通过新的 shell 调用进程,但在 .NET Core 中,进程是直接在现有可执行文件中创建的。有一个选项可以更改此设置,称为UseShellExecute。 This is directly from the Microsoft documentation:
true如果在启动进程时应该使用shell;false如果进程应该直接从可执行文件创建。在 .NET Framework 应用上默认为true,在 .NET Core 应用上默认为false。
你可以这样使用它:
var myPythonScript = new Process();
myPythonScript.StartInfo.FileName = @"C:\path\to\my_script.py";
myPythonScript.StartInfo.UseShellExecute = true;
myPythonScript.Start();
当您的 C# 控制台应用程序终止时,您的 python 脚本应该仍在运行。
感谢 Panagiotis Kanavos,他让我意识到 UseShellExecute 与进程之间的父/子关系无关。因此,我使用 .NET Core 在本地设置了一个沙箱并对其进行了一些尝试,这对我有用:
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();
当父应用终止时,我的 python 脚本仍在后台运行。
【讨论】:
directly from the executable file,表示从epath参数传入的文件中。没有尝试找到可以处理文件扩展名的应用程序。绝对不是directly inside the existing executable。不能在进程中创建进程。
UseShellExecute 是一罐蠕虫。 UseShellExecute + 脚本不适用于较新的版本。见github.com/dotnet/corefx/issues/24704。在最近的版本中,它使用 xdg-open 而不是 bash -c :( 我建议手动调用 bash,但我怀疑我们会遇到 OP 的问题(递归!)