sanguine
sanguine

Reputation: 107

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?

Upvotes: 0

Views: 1315

Answers (2)

Bryan Laygond
Bryan Laygond

Reputation: 111

To check if a specific key was pressed in pynput, you must first filter the key as an alphanumeric or a special key.

After that, it is just a matter of listing your conditions either under on_press or on_release callback functions.

The following example code makes use of a helper function for the alphanumeric filtering, and presents conditions for a few keys under on_release

from pynput.keyboard import Key, Listener
keys_saved = [] #empty list

#--- Helper Function ---
def alphanumeric_filter(key):
    '''
    Return alphanumeric keys as a char type and special keys as a key type
    '''
    try:
        return key.char
    except AttributeError:
        return key

# Callback functions needed for Keyboard Listener
def on_press(key):         
    key = alphanumeric_filter(key)
    print('{} was pressed'.format(key))
              
def on_release(key):            
    key = alphanumeric_filter(key)
    print('{} was released'.format(key))
    
    # ADD ALL YOUR CONDITIONS HERE
    if key == Key.esc or key== 'q':
        return False # Stop listener
    if key == 'a':
        print("EXCLUSIVE MESSAGE for alphabet key = a")
    if key == '1':
        print("EXCLUSIVE MESSAGE for number key = 1")
    if key == Key.space:
        print("EXCLUSIVE MESSAGE for special key = Key.space")
    
    # In your case
    if key in ['w','a','s','d']:
        keys_saved.append(key)
        print(keys_saved)
       
    
print('Keyboard Listener started... ')
with Listener(on_press = on_press,
              on_release = on_release) as listener:                    
    listener.join()

Upvotes: 0

Noé Mastrorillo
Noé Mastrorillo

Reputation: 309

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()

Upvotes: 3

Related Questions