简体   繁体   中英

How to make on_release events truly non-blocking inpynput?

My use case is, I'm using pynput/Python to make a reaction time registration application. The essence is that someone will press a control key to mark the first time epoch, and then the reactor hits any other key, and the time difference between the two keystrokes will be computed and displayed.

In order to alert the reactor to press a key, I am playing a tone that is about 1 second long when the initiator releases their key. However, since reaction time is on the order of milliseconds, I don't want them to have to wait for the tone to complete to press the button as they currently must, or even initiate a new set of two keystrokes. As soon as the sound fires, you should be free to press more keys.

In this sense, I can't figure out how to make the events non-blocking. Using the listener.start() paradigm doesn't seem to help me here. Code is below:

from pynput import keyboard
from datetime import datetime
from playsound import playsound

INITIATE = {keyboard.Key.enter}

def on_press(key):
        global initiated_time
        pressed_time = None
        reaction_time = None

        if key in INITIATE:
                initiated_time = datetime.now()
                return initiated_time
        else:
                pressed_time = datetime.now()
                reaction_time = pressed_time - initiated_time
                reaction_time_ms = int(reaction_time.seconds) * 1000 + int(reaction_time.microseconds)/1000
                print('Reaction time %s ms' % (reaction_time_ms))

def on_release(key):
        if key in INITIATE:
                playsound('bong.mp3')
        print('')

with keyboard.Listener(
on_press=on_press,
on_release=on_release
) as listener:
        listener.join()

According to the docs here , playsound has a default argument, block, which will play the sound asynchronously if set to False, meaning it will not prevent your script from continuing to run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM