user12824087
user12824087

Reputation:

How to detect keypress/release in pynput

I am using pynput to detect keypress release but I want to execute some different code on release of a specific key.

Here is my code:

1   from pynput import keyboard
2
3   def on_press(key):
4        try:
5           print('Key {0} pressed'.format(key.char))
6           #Add your code to drive motor
7       except AttributeError:
8           print('Key {0} pressed'.format(key))
9           #Add Code
10  def on_release(key):
11      print('{0} released'.format(key))
12      #Add your code to stop motor
13      if key == keyboard.Key.esc:
14          # Stop listener
15          # Stop the Robot Code
16          return False
17      if key == keyboard.Key.Qkey:
18          print ("fviokbhvxfb")
19
20  # Collect events until released
21  with keyboard.Listener(
22          on_press=on_press,
23          on_release=on_release) as listener:
24      listener.join()

they point which does't work is this :

if key == keyboard.Key.Qkey:
    print ("fviokbhvxfb")`

probably my problem is the Qkey.

i have written at line 17 what should i replace it with? I am trying to detect if q is released and pressed and execute some code only if it is pressed down and not something else.

Upvotes: 3

Views: 11735

Answers (1)

Vicrobot
Vicrobot

Reputation: 3988

You can do this:

def on_release(key):
    print('{0} released'.format(key))
    #Add your code to stop motor
    if key == keyboard.Key.esc:
        # Stop listener
        # Stop the Robot Code
        return False
    if 'char' in dir(key):     #check if char method exists,
        if key.char == 'q':    #check if it is 'q' key
            print("fviokbhvxfb")

Upvotes: 3

Related Questions