Search code examples
pythondictionarykeylistenerpynput

Make specific Key method constraint on pynput.Listener work in conjunction with dictionary in python


I am trying to use the restriction of if(key == Key.left or key == Key.up): to log into log.txt only the keys Key.up and Key.left. I wanted to add a dictionary so that Key.up is U and Key.left is L. Since then I have a error: when I use keylogger.py it says File "keylogger.py", line 27, in writeLog keydata = keydata.replace("'", "") UnboundLocalError: local variable 'keydata' referenced before assignment. And when I use keylogger2.py if(key == Key.left or key == Key.up): it doesn't cause restriction that I wanted.

keylogger.py:

from pynput.keyboard import Listener, Key

#setting the 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
     '' '

    # dictionary with keys to translate
    translate_keys = {
        "Key.up": "U",
        "Key.left": "L",
    }
    if(key == Key.left or key == Key.up):
#convert the keystroke to string
      keydata = str(key)

#removing single quotes delimiting characters
    keydata = keydata.replace("'", "")

    for key in translate_keys:
         #key gets dictionary key translate_keys
         #replace key with its value (translate_keys [key])

        keydata = keydata.replace(key, translate_keys[key])

    #open the 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()

keylogger2.py modified with dictionary inserted


from pynput.keyboard import Listener, Key


logFile = "/home/diego/log.txt"

def writeLog(key):
    translate_keys = {
        "Key.up": "U",
        "Key.left": "L",
    }
    if(key == Key.left or key == Key.up):

      keydata = str(key)

    keydata = keydata.replace("'", "")

    for key in translate_keys:
        keydata = keydata.replace(key, translate_keys[key])

    with open(logFile, "a") as f:
        f.write(keydata)

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

How can I make the restriction if(key == Key.left or key == Key.up): work in conjunction with the dictionary translate_keys = {"Key.up": "U","Key.left": "L",} ?


Solution

  • You can remove the quotes and compare the objects directly as shown below

    def writeLog(key):
        translate_keys = {
            Key.up: "U",
            Key.left: "L",
        }
        if key in translate_keys:
            with open(logFile, "a") as f:
                f.write(translate_keys[key])