- 1 year ago
Python 3.6 ~ AttributeError: module 'servicemanager' has no attribute 'Initialize' ~ When creating windows service exe
The error AttributeError: module 'servicemanager' has no attribute 'Initialize'
typically occurs when trying to use the servicemanager.Initialize
method in Python but it's not available. This issue is commonly encountered when using Python 3.6 or later versions on Windows.
In Python 3.6 and later, the servicemanager
module was removed, resulting in the error you encountered. Instead, you can use the win32service
module from the pywin32
library to create Windows services.
To resolve this issue, follow these steps:
Install the
pywin32
library: Open a command prompt and run the following command to install thepywin32
library:pip install pywin32
Modify the code that uses
servicemanager.Initialize
: Update your code to use thewin32service
module frompywin32
instead ofservicemanager
. Thewin32service
module provides the necessary functions to create and manage Windows services.Here's an example of how you can modify your code:
pythonimport win32serviceutil
import win32service
import win32event
class MyService(win32serviceutil.ServiceFramework):
_svc_name_ = 'MyService'
_svc_display_name_ = 'My Service'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
Update the code according to your specific requirements for the Windows service.
Create the Windows service executable: Open a command prompt and run the following command to create the Windows service executable:
csspyinstaller --onefile your_script_name.py
Replace
your_script_name.py
with the name of your Python script.
This approach should resolve the AttributeError: module 'servicemanager' has no attribute 'Initialize'
error when creating a Windows service with Python 3.6 or later versions. By using the win32service
module from the pywin32
library, you'll have the necessary functionality to create and manage Windows services.