Search code examples
pythonwindows-servicespywin32

Python service error when importing packages


I'm trying to set up a service using pywin32 and I keep getting an error when importing packages. This is the script I'm using (I got it from another question in SO):

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket

class AppServerSvc (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):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

This dummy service works as intended after installing. However, when I import the necessary dependencies (say just import numpy as np), I can install the service just fine but it throws an error when it gets started. (this is the error)

Just for clarification, I've tried every single solution offered in other SO posts about this (there are a ton!). I'm not using a venv; everything (script, Python installation) is on the C: drive; and I've copied the corresponding .dll files from Python39\Lib\site-packages\pywin32_system32 to Python39\Lib\site-packages\win32. Also, just to mention, if I use debugging with python service.py debug, the service works just fine. I guess it could be a problem with package paths, but I've also looked at the environment variables and I don't see anything wrong.

Thanks in advance


Solution

  • Okay, so I fixed my problem, this is what worked for me. Basically, for some reason some packages (like numpy) weren't installed in the main location (Python39\Lib\), this is likely due to the fact that whoever installed these didn't do it from an elevated cmd prompt: instead they were installed in C:\Users\MyUser\AppData\Roaming\Python\.... I didn't think this was too problematic though, as those paths were considered in the environment variables. However, when running my script as a service, the paths considered didn't take this path into account, and thus the modules weren't being found. Since there's no stdout, in order to see this I wrote the output of sys.path on a file, this was done inside the main definition.

    Fixing is really simple, just uninstall all affected packages (in my case numpy, pandas and SQLAlchemy) and install them from an elevated cmd.