7

I'm fairly new to Python and I have a python script that I would like to ultimately convert to a Windows executable (which I already know how to do). Is there a way I can write something in the script that would make it run as a background process in Windows instead of being visible in the foreground?

6
  • 1
    You are asking two different questions here. One is how to make the Python script run in the background, and the other is how to convert it to a WIndows executable. Can you please clarify if you need one or the other (they are completely independent). Commented Aug 28, 2017 at 4:49
  • @BurhanKhalid Sure, just edited it. Commented Aug 28, 2017 at 4:53
  • 1
    Read about packaging Python programs into single executables (e.g. pyinstaller, cx_freeze). You can also write a Windows service. Commented Aug 28, 2017 at 4:53
  • Are you asking how to create a Windows service, or how to simply run it in the background? A "background process in Windows" is usually a service, but you can run any script in an infinite loop via the task manager or scheduler and it will happily run in the background. So please can you clarify what you are really looking for? Commented Aug 28, 2017 at 4:53
  • @BurhanKhalid I would like to make the python script run as usual but without the user being able to see it Commented Aug 28, 2017 at 4:56

2 Answers 2

1

You can always run a Windows program in the background using

START /B program

See this post for more information.

Sign up to request clarification or add additional context in comments.

4 Comments

And you can even use os.system("START /B "+sys.argv[0]+" --backgrounded") if this flag not exists else drop that flag.
stdin will still be the console input buffer, which may be a problem. Use start "title" /b [command line] < NUL to redirect stdin to the NUL device. Unlike Unix, however, if the program tries to read from stdin, it will not be suspended. There's no shell job that allows bringing the process back to the foreground.
Also, remaining attached to the console means the application will unavoidably be killed when the console window is closed. Due to the way Python handles signals, it can't even be notified via the C runtime's SIGBREAK signal (to clean up and exit gracefully, etc). It would have to set a low-level console control handler via ctypes or PyWin32.
Adding to above, You can run the same in powershell. Start-Process python -ArgumentList "python-script-file-path" -NoNewWindow. Start-Process is alias to start
0

You can run the file using pythonw instead of python means run the command pythonw myscript.py instead of python myscript.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.