Skip to content

Instantly share code, notes, and snippets.

@dishantrathi
Last active July 27, 2023 01:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dishantrathi/227c449bf43e77e5e02b1ee3ab3e28c9 to your computer and use it in GitHub Desktop.
Save dishantrathi/227c449bf43e77e5e02b1ee3ab3e28c9 to your computer and use it in GitHub Desktop.
Creating a Windows Service with Python

Creating a Windows Service with Python 3

Requirements

Build

(env)$ pyinstaller -F --hidden-import=win32timezone WindowsService.py

Run

(env) dist\WindowsService.exe install
Installing service TestService
Service installed

(env) dist\WindowsService.exe start
Starting service TestService

Clean

(env) dist\WindowsService.exe stop
(env) dist\WindowsService.exe remove

Use Cases / Examples

  • File Sync Service
  • Ping Service
  • FTP <> Database Sync Service
  • System Performance Monitoring Service
  • Client - Server Endpoint Services (Custom - SSH over endpoint)
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService" #Service Name (exe)
_svc_display_name_ = "Test Service" #Service Name which will display in the Winfows Services Window
_svc_description_ = "My service description" ##Service Name which will display in the Winfows Services Window
def __init__(self, args):
'''
Used to initialize the service utility.
'''
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
'''
Used to stop the service utility (restart / timeout / shutdown)
'''
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
'''
Used to execute all the piece of code that you want service to perform.
'''
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment