detect key press in python, where each iteration can take more than a couple of seconds?(在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间?)
                            本文介绍了在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
编辑:以下使用keyboard.on_press(Callback,Suppress=False)的答案在ubuntu中运行正常,没有任何问题。 但在Redhat/Amazon Linux中,它无法工作。
我已经使用了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
但上面的代码要求每次迭代在纳秒内执行。在以下情况下失败:
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
推荐答案
您可以在keyboard模块中使用事件处理程序来达到预期效果。
一个这样的处理程序keyboard.on_press(callback, suppress=False):
它为每个key_down事件调用一个回调。
有关详细信息,请访问keyboard docs
以下是您可以尝试的代码:
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
这篇关于在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:在Python中检测按键,其中每次迭代可能需要几秒
 
				
         
 
            
        基础教程推荐
             猜你喜欢
        
	     - 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				