обнаружить нажатие клавиши в python, где каждая итерация может занять более пары секунд? - PullRequest
6 голосов
/ 02 марта 2020

Редактировать: Приведенный ниже ответ для использования keyboard.on_press (callback, suppress = False) отлично работает в Ubuntu без каких-либо проблем. Но в Redhat / Amazon linux он не работает.

Я использовал фрагмент кода из этого потока

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

Но приведенный выше код требует, чтобы каждая итерация выполнялась в наносекундах. Ошибка в следующем случае:

import keyboard  # using module keyboard
import time
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break

Ответы [ 3 ]

5 голосов
/ 02 марта 2020

Вы можете использовать обработчики событий в модуле keyboard для достижения желаемого результата.

Один из таких обработчиков: keyboard.on_press(callback, suppress=False): который вызывает обратный вызов для каждого key_down событие. Вы можете обратиться к документация по клавиатуре

Вот код, который вы можете попробовать:

import keyboard  # using module keyboard
import time

stop = False
def onkeypress(event):
    global stop
    if event.name == 'q':
        stop = True

# ---------> hook event handler
keyboard.on_press(onkeypress)
# --------->

while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if stop:  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break
0 голосов
/ 14 марта 2020

Редактировать: не берите в голову, другой ответ использует почти такой же подход

Это то, что я мог бы придумать, используя тот же модуль "клавиатура", см. Комментарии в коде ниже

import keyboard, time
from queue import Queue 

# keyboard keypress callback
def on_keypress(e): 
    keys_queue.put(e.name)

# tell keyboard module to tell us about keypresses via callback
# this callback happens on a separate thread
keys_queue = Queue() 
keyboard.on_press(on_keypress)

try:
    # run the main loop until some key is in the queue
    while keys_queue.empty():  
        print("sleeping")
        time.sleep(5)
        print("slept")
    # check if its the right key
    if keys_queue.get()!='q':
        raise Exception("terminated by bad key")
    # still here? good, this means we've been stoped by the right key
    print("terminated by correct key")
except:
    # well, you can 
    print("#######")
finally:
    # stop receiving the callback at this point
    keyboard.unhook_all()
0 голосов
/ 02 марта 2020

Вы можете использовать поток

import threading

class KeyboardEvent(threading.Thread):
    def run(self):
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop

keyread = KeyboardEvent()
keyread.start()

Это будет работать параллельно с чем-либо в главном потоке и будет посвящено прослушиванию нажатия этой клавиши.

...