Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

windows - pyHook + pythoncom stop working after too much keys pressed [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 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...