detect key press in python, where each iteration can take more than a couple of seconds?

Nar*_*u R 4 python redhat keypress python-3.x amazon-linux

Edit: The below answer to use keyboard.on_press(callback, suppress=False) works fine in ubuntu without any issues. But in Redhat/Amazon linux, it fails to work.

I have used the code snippet from this thread

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
Run Code Online (Sandbox Code Playgroud)

But the above code requires the each iteration to be executed in nano-seconds. It fails in the below case:

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
Run Code Online (Sandbox Code Playgroud)

Shu*_*rma 6

您可以使用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
Run Code Online (Sandbox Code Playgroud)

  • 在运行程序之前,执行 sudo su 可以解决问题 (2认同)

Tom*_*Tom -3

你可以使用一个线程

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()
Run Code Online (Sandbox Code Playgroud)

这将与主线程中的任何内容并行运行,并且本质上致力于监听该按键。