Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a KeyCode object to string in python

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
like image 912
Alex Dube Avatar asked Sep 27 '26 07:09

Alex Dube


1 Answers

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()
like image 71
atline Avatar answered Sep 29 '26 20:09

atline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!