我使用下面的python代码,以便程序不断检查是否有一个按键(这类似于unix平台上的非阻塞getch()例程)。当一个适当的键被按下,比如说“p”键,我希望循环暂停。我试图通过使用raw_input命令在注册'p'键后暂停循环来实现这一点。但是,即使有raw_input命令,循环似乎仍在继续而没有暂停。我通过添加一个计数器来验证这一点,该计数器每秒钟将所用时间打印到屏幕上—当循环重新开始时,计数器的持续时间将向前跳转,而不是在暂停之前离开。我不知道我做错了什么。。。任何帮助都是非常感谢的。在
import termios, fcntl, sys, os
import sys
import select
import time
starttime=time.time()
counter=1
pauseflag=0;
while True:
if time.time()-starttime>=counter:
print"Seconds elapsed:", counter
counter=counter+1
try:
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
pausekey = sys.stdin.read(1)
if pausekey=='p':
print"Loop paused"
pauseflag=1
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
if pauseflag==1:
raw_input("Press ENTER to resume loop.") #pause program indefinitely until user hits enter key
pauseflag=0;
这需要多处理或线程,因为您同时要做两件事:1。循环,2。输入并设置标志(您还必须编写一种在两个进程之间进行通信的方法,如多处理管理器字典http://pymotw.com/2/multiprocessing/communication.html)
我认为,在while循环完成之前,您的代码不会执行任何其他操作,但是由于缩进不正确,所以无法判断。在
相关问题 更多 >
编程相关推荐