在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间?

原学程将引见在Python中检测按键,个中每一次迭代能够须要多少秒钟以上的时光?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

在Python中检测按键,其中每次迭代可能需要几秒钟以上的时间? 教程 第1张

成绩描写

编纂:以下应用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(五)
  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模块中应用事宜处置法式去到达预期后果。

1个如许的处置法式keyboard.on_press(callback, suppress=False)
它为每一个key_down事宜挪用1个回调。
有闭具体信息,请拜访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(五)
  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中检测按键,个中每一次迭代能够须要多少秒钟以上的时光?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。