Skip to content

Instantly share code, notes, and snippets.

@guillaumevincent
Last active March 4, 2024 02:08
Show Gist options
  • Save guillaumevincent/d8d94a0a44a7ec13def7f96bfb713d3f to your computer and use it in GitHub Desktop.
Save guillaumevincent/d8d94a0a44a7ec13def7f96bfb713d3f to your computer and use it in GitHub Desktop.
Windows Service with Python 3.5 and pyinstaller

TestService

Windows Service with Python 3.5 and pyinstaller

Requirements

Check

(env)$ python -V
Python 3.5.2

(env)$ pip freeze
PyInstaller==3.2

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
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
_svc_description_ = "My service description"
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)
@nassimmz
Copy link

Hello
Thanks for the script, works perfectly
is there a way to separate it into 2 files: one which is the main script in which the work is done and calls the TestService file and the other is the TestService

I tried doing it but it doesn't seem to work for me, any help would be much appreciated

@guillaumevincent
Copy link
Author

I don't understand the question.
You can try to import your python module (something like: from . import foo, and call the methods you want in SvcDoRun with foo.do_something() no?

If it's not working you need to make the import working with pyinstaller

@MirasSafadi
Copy link

Thank you for this script.
You cannot believe how much time I spent on this simple task!
I was getting 1053 error every time, I tried EVERY solution I found on google, until I found yours.
Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment