Windows - Run process on background after closing cmd

15

4

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?

multigoodverse

Posted 2016-04-26T13:49:08.200

Reputation: 311

Answers

7

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

Posted 2016-04-26T13:49:08.200

Reputation: 365

Where does hide_current_console comes from? Doesn't work on a W10 PC. – Btc Sources – 2019-10-21T09:46:41.790

1I tested it again, it still works. Where it comes from: Please read the post again, I showed the one line of source code this file has and linked a compiled hide_current_console.exe file to download... – CherryDT – 2019-10-22T10:13:46.900

-2

I found the following worked well for me:

run python script.py

nikc

Posted 2016-04-26T13:49:08.200

Reputation: 115

1Oh, and on Linux instead of background (&) and disown I would suggest using nohup. – nikc – 2017-08-10T06:01:37.677

5That command entered into a Windows cmd shell gives the following error: 'run' is not recognized as an internal or external command, operable path or batch file.. – markshep – 2018-01-10T12:55:17.400