#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
# Do anything else you want to do here
print('Done')
import select
import sys
def times(f): # f: file descriptor
after = 0
while True:
changes = select.select([f], [], [], 1)
if f in changes[0]:
data = f.readline().strip()
if data == "q":
break
else:
print "After", after, "seconds you pressed", data
after += 1
times(sys.stdin)
来自http://www.swaroopch.com/notes/Python_en:Control_Flow
如果您想不断地查找用户输入,您将需要multithreading。
示例:
如你所见,你的信息会有点混乱,比如:
因为有两个线程同时写入stdoutput。要同步它们,需要^{} :
好吧,现在最好:
请注意,在输入命令以进入“输入模式”之前,您需要按
Enter
。也许select.select正是您所要寻找的,它会检查文件描述符中是否有准备好读取的数据,以便您只能读取它所处的位置,而不需要中断处理(在本例中,它会等待一秒钟,但将1替换为0,它将工作得很好):
相关问题 更多 >
编程相关推荐