使用thread和terminal capabilities可以编写(按任意键停止):
import thread
import time
def read_key():
import termios
import sys
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] &= ~(termios.ICANON | termios.ECHO) # c_lflags
c = None
try:
termios.tcsetattr(fd, termios.TCSANOW, new)
c = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSANOW, old)
return c
def input_thread():
read_key()
thread.interrupt_main()
def countup():
try:
thread.start_new_thread(input_thread, ())
for i in range(1000000):
print i
time.sleep(1)
except KeyboardInterrupt:
Z = raw_input("restart timer? ")
if Z == 'y' or Z == 'Y':
countup()
让我们澄清一下:
thread.start_new_thread()使用input_thread()作为启动函数创建一个新线程.在thread.interrupt_main()时,在主线程中引发KeyboardInterrupt.
termios.tcgetattr()返回当前终端属性. ?termios.ICANON取消设置canonical模式,?termios.ECHO阻止输入打印,然后termios.tsetattr()进行更改.
或者,在Windows上,可以使用msvcrt中的getch()代替read_key()
def input_thread():
msvcrt.getch()
thread.interrupt_main()
参考