20

I have a Python script which I want to run as a background process on Windows.

I can do that on Linux with:

python script.py &

and then disconnect the process from the terminal with:

disown

On Windows, all I have so far is this:

start /b python script.py

However, if I close the CMD window, the script stops running. Is there any extra command that I am missing here to keep the script running on the background?

2 Answers2

10

start should already be the right direction. However, /b attaches it to the same console. Now the problem is that when a console window is closed, any process associated with this console will also be closed.

You can either use start without /b, then it will run in a new console. If you want to run it in the background without a console window though, then you would need to use a VBScript or third-party tool: Run a batch file in a completely hidden way

However, in that case you wouldn't see the stdout/stderr output anymore. You could redirect it to a file though, by wrapping it in a cmd /c your_command > stdout.txt 2> stderr.txt call and starting this one through one of the aforementioned methods (VBScript, third-party tool, ...).

Alternatively, you could also hide your own console window before you exit. I just wrote a little one-line program which does exactly that (source code is basically ShowWindow(GetConsoleWindow(), SW_HIDE)): http://share.cherrytree.at/showfile-24286/hide_current_console.exe

This way, you can use start /b, and when you want to "close" your console (technically hide it), you would run hide_current_console & exit which would hide the console and then close the cmd.exe process (not the python process) - in one line, since you can't type exit after the console was already hidden.

CherryDT
  • 534
-1

I found the following worked well for me:

run python script.py

NOTE: This requires cygwin

Sooth
  • 153