按键并等待固定的时间 [英] Key press and wait for a fixed amount of time
问题描述
我想让python程序在每个循环周期中等待1英寸(不必是实时的,所以我对time.sleep(1)的准确性没问题)之后,我想知道是否有键被按下,如果是这样的话.
I want to make a python program wait 1'' per loop cycle (doesn't have to be real time so i'm fine with time.sleep(1) accuracy) after that I would like to know if a key was pressed and if so which one.
I found a solution here Python wait x secs for a key and continue execution if not pressed, but it's not exactly my problem. Since when the button is pressed I still want to wait the remainder of the second.
OS:Win 7-但最好是跨平台的(至少对ubuntu而言)
OS: Win 7 - but preferably crossplatform (at least to ubuntu)
我确实尝试过msvcrt
,但这对我来说似乎很笨拙,我想知道是否不存在任何更直接的前瞻方法.当然,我不是第一个遇到此问题的人.
I did try msvcrt
but this seems rather clumsy to me and I was wondering if there doesn't exist any more straight foreward method. Surely I'm not the first one with this problem.
推荐答案
这是一个使用线程的简单示例.
Here's a simple example using threads.
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()
这篇关于按键并等待固定的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!