Windows - Run process on background after closing cmd

48,096

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.

Share:
48,096

Related videos on Youtube

multigoodverse
Author by

multigoodverse

Updated on September 18, 2022

Comments

  • multigoodverse
    multigoodverse over 1 year

    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?

  • nikc
    nikc over 6 years
    Oh, and on Linux instead of background (&) and disown I would suggest using nohup.
  • markshep
    markshep over 6 years
    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..
  • Btc Sources
    Btc Sources over 4 years
    Where does hide_current_console comes from? Doesn't work on a W10 PC.
  • CherryDT
    CherryDT over 4 years
    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...