使 pynput.Listener 上的特定键方法约束与 python 中的字典一起工作

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

我正在尝试使用 if(key == Key.left or key == Key.up): 的限制登录到 log.txt,仅密钥 Key.upKey.left。我想添加一个字典,以便 Key.up 是 U 并且 Key.left 是 L。从那时起我有一个错误:当我使用 keylogger.py 它说 File "keylogger.py", line 27, in writeLog keydata = keydata.replace("'", "") UnboundLocalError: local variable 'keydata' referenced before assignment。当我使用 if(key == Key.left or key == Key.up): 时,它不会造成我想要的限制。

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

插入字典修改


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

如何使限制 if(key == Key.left or key == Key.up): 与字典 translate_keys = {"Key.up": "U","Key.left": "L",} 结合使用?

您可以删除引号并直接比较对象,如下所示

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

你可以这样做:

translate_keys = {
    str(Key.up): "U",
    str(Key.left): "L"
}
if(key == Key.left or key == Key.up):
    keydata = translate_keys[str(key)]

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