python - 模块未找到错误: No module named 'win32serviceutil'

标签 python python-3.x windows

我有一个可以作为 Windows 服务安装的项目,但我在完成它时遇到了麻烦。

Venv 已为此项目做好准备,并安装了 pywin32 软件包(版本 227)。然而,当我尝试从控制台运行 python 文件时:

import win32serviceutil

我收到以下错误:

ModuleNotFoundError: No module named 'win32'

我尝试过的事情:

  • 重新安装软件包,并使用python -m pip install pywin32重新安装
  • 将导入方式更改为:

    从 win32 导入 win32serviceutil 从 win32.lib 导入 win32serviceutil 导入 win32.lib.win32serviceutil 作为 win32serviceutil

  • 来自this thread的回答

win32 被 PyCharm 识别为文件夹:

enter image description here

奇怪的是,我可以运行以下命令并安装 Windows 服务:

python MyPythonFile.py install

它不会返回任何错误。但是尝试使用命令启动服务:

python MyPythonFile.py start

返回:

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

在 Debug模式下python MyPythonFile.py debug它返回:

ModuleNotFoundError: No module named 'win32serviceutil'

最佳答案

该线程的解决方案有效: Using PythonService.exe to host python service while using virtualenv

我用来解决它的代码:

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

此代码必须在导入错误之前运行

关于python - 模块未找到错误: No module named 'win32serviceutil' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59047849/

相关文章:

python - 如何在 plotly 中添加条形图上方的百分比差异

Python将一个变量内的多个列表合并为一个列表

python-3.x - Win 10 : Cmd can bring windows to foreground, 但任何其他终端都不能(即使已提升)。为什么会这样?

c++ - 从 COM 类继承

python - 使用Python多行解析Xml

python - 使用堆进行大磁盘排序

python - 是否可以将新的键/值添加到字典的开头而不是后面

python - 如何根据一周中不同日期的不同时间段修剪数据集?

linux - 如何获得捕捉 SIGABRT 的信号

c++ - C++ 中的 Windows LDAP 身份验证