Search code examples
pythonlistenerkeyloggerpynput

Listening to specific keys with pynput.Listener and keylogger?


I have the following python script below:

But I want to "listen" or, if it's enough, just "record" to my log.txt, the following keys: Key.left and Key.up. How can I cause this restriction?

This question is similar but the code structures of her responses are somewhat different and would require a major change to allow the keylogger and this restriction on the Listener.

And this other question seems to me to be a potential source of inspiration for finding a method of solution.

I spent some time looking for a question that would give me this answer or help me to reflect on it but I couldn't find it but if there is a question already published please let me know!

How to create a Python keylogger:

#in pynput, import keyboard Listener method
from pynput.keyboard import Listener

#set log file location
logFile = "/home/diego/log.txt"

def writeLog(key):
    '''
    This function will be responsible for receiving the key pressed.
     via Listener and write to log file
    '''

    #convert the keystroke to string
    keydata = str(key)

    #open log file in append mode
    with open(logFile, "a") as f:
        f.write(keydata)

#open the Keyboard Listener and listen for the on_press event
#when the on_press event occurs call the writeLog function

with Listener(on_press=writeLog) as l:
    l.join()

Solution

  • You can import Key module from pynput.keyboard and check for the type of key-strokes.

    #in pynput, import keyboard Listener method
    from pynput.keyboard import Listener, Key
    
    #set log file location
    logFile = "/home/diego/log.txt"
    
    def writeLog(key):
        '''
        This function will be responsible for receiving the key pressed.
         via Listener and write to log file
        '''
    
        if(key == Key.left or key == Key.up):
            #convert the keystroke to string
            keydata = str(key)
    
            #open log file in append mode
            with open(logFile, "a") as f:
                f.write(keydata)
    
    #open the Keyboard Listener and listen for the on_press event
    #when the on_press event occurs call the writeLog function
    
    with Listener(on_press=writeLog) as l:
        l.join()