I\'m trying to write a windows Service in python, but the tricky part is i want to deploy it on a machine that doesn\'t have python. I\'ve successfully created a service like th
tldr Python 3.5 Windows Service build with pyinstaller : gist
Here a simple Windows Service with python :
WindowsService.py
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
rc = None
while rc != win32event.WAIT_OBJECT_0:
with open('C:\\TestService.log', 'a') as f:
f.write('test service running...\n')
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
Create an exe with pyinstaller (pip install pyinstaller
) and python 3.5 :
(env)$ python -V
Python 3.5.2
(env)$ pip freeze
PyInstaller==3.2
(env)$ pyinstaller -F --hidden-import=win32timezone WindowsService.py
Install and run the service
(env) dist\WindowsService.exe install
Installing service TestService
Service installed
(env) dist\WindowsService.exe start
Starting service TestService
Check C:\\TestService.log
file.
Stop and clean
(env) dist\WindowsService.exe stop
(env) dist\WindowsService.exe remove