18

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 Answers 2

9

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.

2
  • Where does hide_current_console comes from? Doesn't work on a W10 PC. Oct 21, 2019 at 9:46
  • 1
    I 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
    Oct 22, 2019 at 10:13
-2

I found the following worked well for me:

run python script.py

NOTE: This requires cygwin

2
  • 1
    Oh, and on Linux instead of background (&) and disown I would suggest using nohup.
    – Sooth
    Aug 10, 2017 at 6:01
  • 7
    That 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
    Jan 10, 2018 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.