Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError: No module named 'win32serviceutil'

I have a project which can be installed as Windows Service, but i have troubles getting it done.

Venv is prepared for this project with pywin32 package installed (version 227). However while I am trying to run a python file from console with:

import win32serviceutil

I am getting a following error:

ModuleNotFoundError: No module named 'win32'

Things I tried:

  • reinstallation of package, and reinstallation with python -m pip install pywin32
  • changing import fashion to:

    from win32 import win32serviceutil from win32.lib import win32serviceutil import win32.lib.win32serviceutil as win32serviceutil

  • Answers from this thread

win32 is recognized as folder by PyCharm:

enter image description here

What is weird, I can run following command and install a Windows Service:

python MyPythonFile.py install

It does not return any errors. However trying to start the service with command:

python MyPythonFile.py start

returns:

"Error 1053: The service did not respond to the start or control request in a timely fashion"

In debug mode python MyPythonFile.py debug it returns:

ModuleNotFoundError: No module named 'win32serviceutil'

like image 711
w8eight Avatar asked Sep 19 '25 04:09

w8eight


1 Answers

The solution from this thread worked: Using PythonService.exe to host python service while using virtualenv

Code which I used to resolve it:

import os
import sys

service_directory = os.path.dirname(__file__)
source_directory = os.path.abspath(service_directory)
os.chdir(source_directory)
venv_base = os.path.abspath(os.path.join(source_directory, "..", "..", "venv"))
sys.path.append(".")
old_os_path = os.environ['PATH']
os.environ['PATH'] = os.path.join(venv_base, "Scripts")+ os.pathsep + old_os_path
site_packages = os.path.join(venv_base, "Lib", "site-packages")
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = venv_base
new_sys_path = list()
for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path

This code has to run before faulting imports

like image 81
w8eight Avatar answered Sep 20 '25 19:09

w8eight