按下一个键激活键盘记录器并让它 运行 持续一段时间

activate keylogger with the press of a key and have it running for a set amount of time

我想要一个键盘记录器,它通过按下一个键(任何键)激活,然后将在设定时间(例如 10 秒)内按下的所有键保存在一个列表中,然后打印出来。 我试过这个:

from pynput import keyboard
from time import sleep

def on_press(key):
    global recording, keys_pressed
    if not recording:
        recording = True
        sleep(10)
        print(" ".join(keys_pressed))
        recording = False


listener = keyboard.Listener(
    on_press=on_press)
listener.start()


def on_release(key):
    global recording
    if recording:
        print("key pressed")
        global keys_pressed
        Key = str(key)
        if Key.startswith("Key."):
            keys_pressed.append(Key[4:].strip("'"))
        else:
            keys_pressed.append(str(key).strip("'"))

listener2 = keyboard.Listener(
    on_release=on_release)
listener2.start()

keys_pressed = []

recording = False

while True:
    pass

它有点管用,但它会多次打印我显然不想要的列表。程序运行起来也特别慢

如果您知道任何解决方案,请告诉我。

它多次打印我显然不想要的列表

你明确要求它在每次按下按钮时打印列表

print(" ".join(keys_pressed))

此外,我无法理解您为什么要尝试实现 2 个侦听器???

我会做更多类似的事情,尽管我确信还有更漂亮的解决方案!

from pynput import keyboard
from time import time

my_log = []
started = False
start_time = time() # just here to initialize, won't be used until started = True

def on_press(key):
    global started
    global start_time
    if started is False:
        started = True
        start_time = time()
        print("starting timer")
    try:
        character = '{0}'.format(key.char)
    except AttributeError:
        character = '{0}'.format(key)
    my_log.append(character)


def listen():
    global started
    print('keyboard listener is initialized')
    with keyboard.Listener(on_press=on_press):
        while True:
            if started:
                now = time()
                if now - start_time > 10:
                    break
        return # end our listener

listen()
print("done listening")
print(my_log)

示例输出看起来像(有点乱,因为打印与键入的内容相结合):

keyboard listener is initialized
astarting timer
bcdefghijklmnopqrstuvwxyzdone listening
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']