Search code examples
pythonpynput

Listen for a specific key using pynput keylogger?


I'd like to create a key logger that would listen for the keys 'w' 'a' 's' 'd' and whenever it detects these keys, adds them to a list. So far I have this code

from pynput.keyboard import *
keys_pressed=[]
def on_press(key):
        print(key)

def on_release(key):
    if key==Key.esc:
        return False

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

How could I check if a specific key is pressed, and add it to the keys_pressed list?


Solution

  • You can use KeyCode.from_char(char) to get the key from the specified char. So KeyCode.from_char('w') would return the key for w.

    Then you can store your keys corresponding to W, A, S and D in a list or whatever and check in your callback if the pressed key equals to one of these.

    Here is an example:

    from pynput.keyboard import *
    
    keys = [KeyCode.from_char(c) for c in 'wasd']
    
    def on_press(key):
        if key in keys:
            print(f'good key: {key}')
        else:
            print(f'bad key: {key}')
    
    def on_release(key):
        if key==Key.esc:
            return False
    
    with Listener(on_press=on_press,on_release=on_release) as listener:
        listener.join()