如何在不使用“输入”的情况下检测输入;输入“;用python?
我正在尝试通过使用while循环来计算时间,从而完成一个高速摄影机程序。我希望用户能够输入“Enter”来停止while循环,而不需要while循环暂停并等待用户输入内容,因此while循环可以作为时钟工作如何在不使用“输入”的情况下检测输入;输入“;用python?,python,input,Python,Input,我正在尝试通过使用while循环来计算时间,从而完成一个高速摄影机程序。我希望用户能够输入“Enter”来停止while循环,而不需要while循环暂停并等待用户输入内容,因此while循环可以作为时钟工作 import time timeTaken=float(0) while True: i = input #this is where the user either choses to input "Enter"
import time
timeTaken=float(0)
while True:
i = input #this is where the user either choses to input "Enter"
#or to let the loop continue
if not i:
break
time.sleep(0.01)
timeTaken=timeTaken+0.01
print(timeTaken)
我需要一行代码,它可以检测用户是否在不使用“输入”的情况下输入了内容。如果您要收听输入并同时处理其他内容,则应使用线程。至少有两种方法 第一种方法是检查“标准输入”流是否有一些数据,而不是阻塞以实际等待有一些数据。评论中引用的答案告诉您如何处理此问题。然而,尽管这在简单性方面很有吸引力(与其他选择相比),但在Windows和Linux之间没有透明的可移植性 第二种方法是使用线程阻止并等待用户输入:
import threading
import time
no_input = True
def add_up_time():
print "adding up time..."
timeTaken=float(0)
while no_input:
time.sleep(0.01)
timeTaken=timeTaken+0.01
print(timeTaken)
# designed to be called as a thread
def signal_user_input():
global no_input
i = raw_input("hit enter to stop things") # I have python 2.7, not 3.x
no_input = False
# thread exits here
# we're just going to wait for user input while adding up time once...
threading.Thread(target = signal_user_input).start()
add_up_time()
print("done.... we could set no_input back to True and loop back to the previous comment...")
如您所见,如何从线程到接收到输入的主循环进行通信有点进退两难。全局变量来通知它。。。yucko呃?好吧,我对编程不太了解,我在为我的GCSE做准备,所以是的,我需要一些东西给我解释一下。你是什么意思?我的意思是,为了让while循环继续,如果你还想从stdin读取,你必须在一个单独的线程中运行它。可能是重复的井我只想输入而不暂停程序。看看。搜索的正确关键字是“python非阻塞键盘输入”,每个查找或多或少都指向
select
模块。@MaxDickson«我只需要输入。。。不暂停»思考:当您准备好处理输入时,检查stdin
是否有一些数据,或者在不阻塞(暂停)的情况下读取数据,或者继续执行其他必须执行的操作。@GreenAsJade我查看了您的编辑。。。难道不能对编辑进行投票吗?如果我能做到,我会很高兴的!干得好!有一个问题,add\u-up\u-time
中的循环是按照您编写的方式编写的,或者在没有输入的情况下也是这样:…?提前谢谢。真的:)我从最初开始,并没有充分地优化,是吗?