我正在尝试制作一个简单的计时器,该计时器一直计数到被键盘输入打断为止.
I am trying to make a simple timer which counts up until it is interrupted by keyboard input.
现在我正在使用CTRL + C停止计时器,但是我想做一些更简单的事情,例如按空格键或Enter键或任何键".我听说可以通过线程模块完成此操作,但是经过几次尝试,我显然不知道自己在做什么.
right now I am using CTRL+C to stop the timer, but I would like to do something more simple like hitting space or enter or "any key". I hear this can be done with the threading module, but after several attempts I clearly do not know what I am doing with that.
这是我当前的代码:
def countup(): try: a=0 for i in range(1000000) : print i,'\r', time.sleep(1) except KeyboardInterrupt: Z = raw_input("restart timer?" ) if Z == "Y" or Z == "y" : countup()推荐答案
使用线程和终端功能,您可以编写(按任意键停止):
Using thread and terminal capabilities you can write (press any key to stop):
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() 使用作为启动功能.而 thread.interrupt_main() 在主线程中提高KeyboardInterrupt.
termios.tcgetattr() 返回当前终端属性. ~termios.ICANON取消设置规范模式和~termios.ECHO防止输入打印,然后 termios.tsetattr() 进行更改.
termios.tcgetattr() return the current terminal attribute. ~termios.ICANON unset the canonical mode and ~termios.ECHO prevent input print then termios.tsetattr() act the change.
或者,在Windows上,可以在 msvcrt 中使用getch() read_key()
Alternatively, on Windows, getch() from msvcrt can be use in place of read_key()
def input_thread(): msvcrt.getch() thread.interrupt_main()参考
- 线程模块
- Termios模块
- Msvcrt模块
- Thread module
- Termios module
- Msvcrt module
Reference
更多推荐
进行“任何密钥"操作.可互换的Python计时器
发布评论