pythonlistenerevent-listenerpynput

type(list[0]) returns pynput.keyboard._win32.KeyCode


My problem is how pynput returns the data (I hope that's how you would say it?).

So what I'm trying to do is have the listener record keyboard input, then use what letters are added to the list to make a string in word. Although, it seems like the letters aren't strings. Instead they return as pynput.keyboard._win32.KeyCode

Is there a way to convert that to a python readable string or something?
Like if: i typed f, t, w

print(type(list[0]), word)
return 'f', ftw

what it comes out as so far is

f[] pressed
t['f'] pressed
w['f', 't'] pressed
 ['f', 't', 'w'] pressed
['f', 't', 'w'] <class 'pynput.keyboard._win32.KeyCode'> # then basically nothing for word  
[] pressed

from pynput import keyboard


list = []
word = ''.join(list)


def press(key): 
    print(list, 'pressed') 
    if key is not keyboard.Key.space:
        list.append(key)
    elif keyboard.Key.space is key:
        pass
    elif keyboard.Key.enter is key:
        pass


def release(key):
    if key == keyboard.Key.space:
        print(type(list[0]), word)
        if word in hkey:
            func()
        list.clear()

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

Solution

  • You can extract the character from the pressed key by using the char attribute of the pynput.keyboard._win32.KeyCode. In other words, in your press function, you would append key.char to the list. Also, I would avoid using list as a variable name as you may end up with unexpected results from list being the name of a built-in type in Python.

    def press(key):
        print(_list, 'pressed')
        if key is not keyboard.Key.space:
            _list.append(key.char)         # <-- Note: key.char
        elif keyboard.Key.space is key:
            pass
        elif keyboard.Key.enter is key:
            pass