使用 pynput.Listener 和键盘记录器监听特定按键?

Listening to specific keys with pynput.Listener and keylogger?

我有以下 python 脚本:

但我想 "listen" 或者,如果足够的话,只需 "record" 到我的 log.txt,以下键:Key.left 和 Key.up。我怎样才能造成这个限制?

这个 question 很相似,但她的响应的代码结构有些不同,需要进行重大更改以允许键盘记录器和 Listener 上的此限制。

而另一个 question 在我看来是寻找解决方法的潜在灵感来源。

我花了一些时间寻找可以给我这个答案或帮助我反思的问题,但我找不到它,但如果已经发布了一个问题,请告诉我!

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

您可以从 pynput.keyboard 导入 Key 模块并检查击键类型。

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