Introduction
If you want to run a Python script as a Windows service you can use the Non-Sucking Service Manager to create the service.
This application allows you to easily create a service using any executable or batch script that gets
treated as a proper Windows service that you can manage Windows services by running services.msc
or by going to the Services tab from the Task Manager.
The most common use case for running a Python script as a service is to ensure an application is always run and starts running when you log in. For example, if you have a web application that you want to stay running whenever the computer is up. I have used this method to run Flask applications and other utilities.
Setup
Download nssm and extract nssm.exe
.
NSSM is a single file nssm.exe
that does not need any special installation.
For convenience, you may want to place the file inside a directory in your %PATH%
environment variable, otherwise you will need to execute it using the full path.
To learn how to set environment variables in Windows, check out my tutorial
Set Environment Variables in Windows.
You will also need Python installed.
I recommend creating a virtual environment. I usually create at least one virtual environment in
my user's home directory in a directory named venv
. Then I can be sure Python is available in C:\Users\<my_user>\venv\Scripts\python.exe
.
To learn how to setup a Python virtual environment, check out my tutorial
Python Virtual Environments Tutorial.
IMPORTANT: When running nssm
commands, tou need to run the Command Prompt as an Adminstrator. Right click on Command Prompt and choose Run as Administrator.
Create Windows service to run Python script
To create a custom service, you simply need to run nssm install
and tell it the name of your new service
and what program you want to run. In this case we are calling Python from the virtual environment
and running a Python script from my user's home directory.
nssm.exe install "MyCustomService" "C:\Users\nanodano\venv\Scripts\python.exe" "C:\Users\nanodano\myscript.py"
You should see a message that says something like:
Service "MyCustomService" installed successfully!
It will default to have Startup type: Automatic. This means it will start automatically when the computer restarts.
Start and stop your custom service
You can use the normal Services manager services.msc
or you can use NSSM from the Command Prompt.
You can start and stop the service like this:
nssm.exe start MyCustomService
nssm.exe stop MyCustomService
Delete the service
If you no longer want the service you can remove it with the following command:
nssm.exe remove "MyCustomService"
Conclusion
After reading this, you should understand how to create your own custom Windows service to run a Python script using NSSM. You should understand how to create the service and remove it as well as how to start, stop, and restart it. You should understand how to run a specific Python interpreter to run a Python script.