PyHook + pythoncom stops working after pressing too many keys [Python]

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 pressing the key indicated on the keyboard event, or the F2 key as my script, it is pressed several times, the script stops working ...

Does anyone know why? or how to solve it?

I need to restart the script every time this happens, and I need to repeatedly press a key in my script ...

+2
python windows
source share
1 answer

Perhaps you can call the function as Thread to execute asynchronously, add them to your own queue, or set a condition that will not be fulfilled if it is already running, which will stop filling the message that does not work.
Option 1 .. This will add function execution to the thread 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. Otherwise, it will ignore other processing calls if it is 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 have to be careful when adding code to catch exceptions, or the thread will remain blocked.

+2
source share

All Articles