3

I'm trying to trigger functions on key presses in python. I'm using the pynput library's listen function, which returns a Keycode object. I've tried casting the object to string but the following code still returns the following output (when pressing the 'a' key):

def on_press(key):
    mod = str(key)
    print(mod)
    print(type(mod))
    print(mod=='a')

I get:

'a'
< class 'str'>
False
Molly
  • 1,887
  • 3
  • 17
  • 34
Alex Dube
  • 45
  • 1
  • 5
  • Please take a look at this answer. [https://stackoverflow.com/questions/575650/how-to-obtain-the-keycodes-in-python](https://stackoverflow.com/questions/575650/how-to-obtain-the-keycodes-in-python) – Vignesh Krishnan Jan 23 '19 at 05:29
  • Good minimal, weird example. Are you using this as written? or comparing the string to the keycode object directly? – mcint Jan 23 '19 at 05:37

1 Answers1

5

Use next:

def on_press(key):
    print(key.char=='a')

Above will print True.

Your code cannot work just because:

mod = str(key)
print(mod)

Will get 'a', but for a normal string, print('a') will just print a, they are not the same string. You can confirm it with print(len(mod)) & print(len('a'))

BTW, next is a full code for your test:

from pynput.keyboard import Key, Listener
import sys

def on_press(key):
    mod = str(key)
    print(mod)
    print(type(mod))
    print(mod=='a')
    print(key.char=='a')
    print(len(mod))
    print(len('a'))
    sys.exit(0)

def on_release(key):
    pass

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
atline
  • 28,355
  • 16
  • 77
  • 113