Python NameError: name 'keys' is not defined error pynput

Python NameError: name 'keys' is not defined error pynput

我一直在尝试制作键盘记录器,但在 python 脚本 运行 中出现此错误。

File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput_util_init_.py", line 211, in inner return f(self, *args, **kwargs) File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput\keyboard_win32.py", line 280, in process self.on_press(key) File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput_util_init.py", line 127, in inner if f(*args) is False: File "C:\Users\David\Desktop\TESTING\keylogger\main.py", line 16, in on_press keys.append(str(key)) NameError: name 'keys' is not defined Traceback (most recent call last): File "C:\Users\David\Desktop\TESTING\keylogger\main.py", line 43, in listener.join() File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput_util_init_.py", line 259, in join six.reraise(exc_type, exc_value, exc_traceback) File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\six.py", line 702, in reraise raise value.with_traceback(tb) File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput_util_init_.py", line 211, in inner return f(self, *args, **kwargs) File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput\keyboard_win32.py", line 280, in process self.on_press(key) File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput_util_init.py", line 127, in inner if f(*args) is False: File "C:\Users\David\Desktop\TESTING\keylogger\main.py", line 16, in on_press keys.append(str(key)) NameError: name 'keys' is not defined [Finished in 0.614s]

我不知道如何解决这个问题,我已经使用 pip install pyinput 安装了 pyinput,但仍然无法正常工作:/


代码:

    import pynput
from pynput.keyboard import Key, Listener


count = 0
key = []



def on_press(key):

    global keys, count

    keys.append(str(key))


    print("{0} pressed".format(key))

    if count >= 10:
        count = 0
        write_file(keys)
        keys = ()


def write_file(keys):
    with open("log.txt", "w" & "a") as f:
        for key in keys:
            k = str(key).replace("'","")
            f.write(str(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()

感谢任何帮助,谢谢。

我认为您在初始化 keys 列表时有错字。您已将其声明为 key 但您需要 keys.

你需要:

keys = []

而不是:

key = []

因为键实际上没有在任何地方定义

我想你拼错了。

您需要将 key = [] 替换为 keys = []

您在第 6 行中输入错误,因此 keys 没有像错误消息告诉您的那样在任何地方声明(例如 NameError: name 'keys' is not defined)。

第 6 行应该改为 keys = [] of key = []