如何在不使用 time.sleep() 的情况下每秒将值附加到列表中?

How to append value into list every second without using time.sleep()?

global keys_pressed
keys_pressed = []
how_long_moved=[]
def keylogger():
    keys = [KeyCode.from_char(letter) for letter in 'wasd']
    def on_press(key):
        start=time.time()
        if key in keys:
            print(f'good key {key}')
        else: print(f'bad key {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()

我有上面的键盘记录器代码,它将每个 'w a s d' 键都记录为有效键。是否可以在不使用 time.sleep 的情况下每按 1 秒一个键就在列表 how_long_moved 中附加一个随机字母?

你应该使用 non-block thread.And 使用 time.time() 查看时间:

import time
from pynput.keyboard import KeyCode, Key, Controller, Listener
import string, random

global keys_pressed
keys_pressed = []
how_long_moved=[]
def keylogger():
    keys = [KeyCode.from_char(letter) for letter in 'wasd']
    def on_press(key):
        if key in keys:
            print(f'good key {key}')
        else: print(f'bad key {key}')
    def on_release(key):
        if key == Key.esc:
            return False

    listener = Listener(on_press=on_press, on_release=on_release)
    listener.start()

    start_time = time.time()
    controller = Controller()
    all_str = string.ascii_lowercase
    while True:
        if time.time() - start_time >= 1:
            start_time = time.time()
            random_pressed_key = random.choice(all_str)
            controller.press(random_pressed_key)
            how_long_moved.append(random_pressed_key)
            print(how_long_moved)

keylogger()

示例输出:

['d']
good key 'd'
bad key 'g'
['d', 'g']
good key 's'
['d', 'g', 's']
bad key 'b'
['d', 'g', 's', 'b']

由于有两个线程,所以输出的顺序是不规则的(how_long_movedbad key or good key)。