pyHook + pythoncom 在按下太多键后停止工作 [Python] [英] pyHook + pythoncom stop working after too much keys pressed [Python]
问题描述
这是我的脚本:
导入pyHook导入pythoncomhookManager = pyHook.HookManager()定义键盘事件(事件):如果 event.KeyID == 113: # F2#做点什么#返回真hookManager.KeyDown = onKeyboardEventhookManager.HookKeyboard()pythoncom.PumpMessages()
在键盘事件上指定的键,或作为我的脚本的 F2 键被按下几次后,脚本停止工作...
有人知道为什么吗?或者怎么解决?
每次发生这种情况我都必须重新启动脚本,而且我必须在脚本中多次按下按键...
也许你可以将函数作为线程调用来异步执行,将它们添加到你自己的队列或设置一个条件,如果它已经在运行,则不执行,那将停止填充失败的消息泵.
选项 1.这会将函数执行添加到线程队列中:
选项 2. 否则,如果它很忙,这将忽略其他处理呼叫:
<前>定义 myFunc(i):myFunc.isRunning = 真#一些代码myFunc.isRunning = FalsemyFunc.isRunning = Falsedef OnKeyboardEvent(事件):keyPressed = chr(event.Ascii)如果 keyPressed == 'z':如果不是 myFunc.isRunning: #if 函数正在执行忽略此调用t = threading.Thread(target=myFunc,args=(1,))t.start()返回真当然你在通过捕获异常来添加代码时应该小心,否则线程会一直阻塞.
this is my script:
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()
after the key specified on the keyboard event, or the F2 key as my script, is pressed for several times, the script stop working...
Anyone knows why? or how to solve it?
I have to restart the script every time this happens, and I have to press the key a lot in my script...
Maybe you can call the function as a Thread to execute asynchronously, add them to your own queue or set a condition to not execute if it's already running, that will stop filling the messagepump which is that is failing.
Option 1. This will add the function execution to the threads queue:
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()
Option 2. or this will ignore other processing calls if it's busy:
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
of course you should be careful when you add code by capturing exceptions or the thread will stay blocked.
这篇关于pyHook + pythoncom 在按下太多键后停止工作 [Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!