这是我的脚本:
import pyHook
import pythoncom
hookManager = pyHook.HookManager()
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
#do something#
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
在键盘事件上指定的键或我的脚本中的 F2 键被按下几次后,脚本停止工作...
有人知道为什么吗?或者如何解决?
每次发生这种情况时,我都必须重新启动脚本,并且我必须在脚本中多次按键......
最佳答案
也许您可以将该函数作为线程调用以异步执行,将它们添加到您自己的队列中,或者设置一个条件,使其在已经运行的情况下不执行,这将停止填充失败的消息泵。
选项 1。这会将函数执行添加到线程队列中:
import pythoncom, pyHook, threading lock = threading.Lock() def myFunc(i): lock.acquire() #execute next function until previous has finished #some code lock.release() def OnKeyboardEvent(event): keyPressed = chr(event.Ascii) if keyPressed == 'z': t = threading.Thread(target=myFunc, args=(1,)) #added to queue t.start() return True hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages()
选项 2。或者如果繁忙,这将忽略其他处理调用:
def myFunc(i): myFunc.isRunning = True #some code myFunc.isRunning = False myFunc.isRunning = False def OnKeyboardEvent(event): keyPressed = chr(event.Ascii) if keyPressed == 'z': if not myFunc.isRunning: #if function is being executed ignore this call t = threading.Thread(target=myFunc,args=(1,)) t.start() return True
当然,通过捕获异常添加代码时应该小心,否则线程将保持阻塞状态。
关于python - 按下过多按键后 pyHook + pythoncom 停止工作 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3673769/