在 Windows 服务中使用时,pynput 模块的鼠标侦听器不工作。奇怪的是,当我调试服务时,它按预期工作。
考虑以下最小的 python 文件 myService.py:
import servicemanager
import win32serviceutil
import win32service
import win32event
import socket
import pathlib
import sys
import time
from pynput import mouse
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "pynputTest"
_svc_display_name_ = "Test Pynput Listener"
_svc_description_ = "Puh"
logFile = pathlib.Path(r"C:\Data\clicks.log")
def __init__(self,args):
self.isrunning = False
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.stop()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
self.start()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def start(self):
self.isrunning = True
listener = mouse.Listener(
on_click=self.on_mouse_activity)
listener.start()
with open(self.logFile, "a") as fId:
fId.write("start\n")
def stop(self):
self.isrunning = False
with open(self.logFile, "a") as fId:
fId.write("stop\n")
def on_mouse_activity(self, *args):
with open(self.logFile, "a") as fId:
fId.write("click\n")
def main(self):
while self.isrunning:
time.sleep(1)
if __name__ == '__main__':
if len(sys.argv) > 1:
# Called by Windows shell. Handling arguments such as: Install, Remove, etc.
win32serviceutil.HandleCommandLine(AppServerSvc)
else:
# Called by Windows Service. Initialize the service to communicate with the system operator
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(AppServerSvc)
servicemanager.StartServiceCtrlDispatcher()
如果我使用
myService.py install
安装服务,然后使用 myService.py start
启动它,则不会将“点击”写入日志文件。使用 net stop pynputTest
停止服务会将预期的“停止”添加到日志文件中。现在,如果我使用 myService.py debug
调试服务,鼠标点击将被识别,这可以在日志文件中看到。现在我的问题是我需要更改什么才能使其在“正常”Windows 服务中工作。
因为
mouse.Listener
根据文档是一个threading.Thread我也测试了一个简单的线程但是这按预期工作了。
编辑 23 年 4 月 4 日:
我试过这个模块 https://github.com/boppreh/mouse 作为 pynput 的替代品,但结果相同。它在调试时按预期工作,但在 Windows 服务作为普通服务启动时不工作:-(