python 计时器模块_制作“任何键”可互换的Python计时器

使用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()

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值