0

我想要一个键盘记录器,它通过按下一个键(任何键)来激活,然后将在设定的时间量(例如 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

它有点工作,但它多次打印我显然不想要的列表。该程序运行也非常缓慢。

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

4

1 回答 1

2

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

每次按下按钮时,您都明确要求它打印列表

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']
于 2019-04-22T18:21:26.010 回答