按键并等待固定时间
我想写一个Python程序,让它在每次循环的时候等待1秒钟(不需要特别精确,所以用time.sleep(1)就可以了)。之后,我想知道是否有按键被按下,如果有的话,想知道是哪个键。
我在这里找到了一种解决方案 Python等待x秒以检测按键,如果没有按键则继续执行,但这并不完全符合我的需求。因为当按下按钮时,我仍然想等待剩下的那一秒。
操作系统:Windows 7 - 但最好是跨平台的(至少能在Ubuntu上运行)
我试过 msvcrt
,但我觉得这个方法有点笨拙,我在想是否有更简单直接的方法。肯定不是我一个人有这个问题。
1 个回答
1
这里有一个使用线程的简单例子。
import threading
import time
# define a thread which takes input
class InputThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.user_input = None
def run(self):
self.user_input = input('input something: ')
def get_user_input(self):
return self.user_input
# main
it = InputThread()
it.start()
while True:
print('\nsleeping 1s and waiting for input... ')
time.sleep(1)
ui = it.get_user_input()
if ui != None:
print('The user input was', ui)
it = InputThread()
it.start()