进行“任何密钥"操作.可互换的Python计时器

编程入门 行业动态 更新时间:2024-10-28 12:18:15
本文介绍了进行“任何密钥"操作.可互换的Python计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试制作一个简单的计时器,该计时器一直计数到被键盘输入打断为止.

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模块
  • Reference

    • Thread module
    • Termios module
    • Msvcrt module

更多推荐

进行“任何密钥"操作.可互换的Python计时器

本文发布于:2023-10-07 20:07:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   计时器   操作   quot   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!