Windows-关闭cmd后在后台运行进程


15

我有一个Python脚本,希望在Windows上作为后台进程运行。

我可以在Linux上执行以下操作:

python script.py &

然后使用以下命令从终端断开该过程:

disown

在Windows上,到目前为止,我所做的就是:

start /b python script.py

但是,如果我关闭CMD窗口,脚本将停止运行。我在这里缺少任何额外的命令来使脚本在后台运行吗?

Answers:


6

start应该已经是正确的方向。但是,/b将其附加到同一控制台。现在的问题是,当关闭控制台窗口时,与此控制台关联的所有进程也会被关闭。

您可以使用start没有/b,那么它会在一个新的控制台上运行。如果您想在没有控制台窗口的情况下在后台运行它,那么您将需要使用VBScript或第三方工具:以完全隐藏的方式运行批处理文件

但是,在这种情况下,您将不再看到stdout / stderr输出。但是,您可以通过将其包装在cmd /c your_command > stdout.txt 2> stderr.txt调用中并通过上述方法之一(VBScript,第三方工具...)来启动该文件,从而将其重定向到文件。

或者,您也可以在退出之前隐藏自己的控制台窗口。我只是编写了一个单行程序来完成此操作(源代码基本上是ShowWindow(GetConsoleWindow(), SW_HIDE)):http : //share.cherrytree.at/showfile-24286/hide_current_console.exe

这样,您可以使用start /b,并且当您要“关闭”控制台(从技术上将其隐藏)时,将运行hide_current_console & exit该操作,该操作将隐藏控制台,然后关闭cmd.exe进程(而非python进程)-在一行中,因为您无法exit在控制台已隐藏后键入。


哪里hide_current_console来的?在W10 PC上不起作用。
— Btc来源

1
我再次测试,它仍然有效。来源:请再次阅读该帖子,我展示了该文件具有的一行源代码,并链接了已编译的hide_current_console.exe文件以下载...
— CherryDT

-2

我发现以下对我来说很有效:

run python script.py

1
哦,在Linux而不是background(&)上,disown我建议使用nohup。
— nikc

5
在Windows cmd shell中输入的命令给出以下错误:'run' is not recognized as an internal or external command, operable path or batch file.。
— markhep
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.