至少有两种方法可以解决这个问题。在
第一个是检查您的“标准输入”流是否有一些数据,而不是阻塞实际等待有一些数据。评论中引用的答案告诉你如何处理这个问题。然而,虽然这在简单性方面很有吸引力(与其他替代方案相比),但是在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...")
正如您所看到的,在如何从线程到接收到输入的主循环之间进行通信时,存在一些两难的问题。全局变量来指示它。。。恶心,嗯?在