Skip to main content
 首页 » 编程设计

python之使用空格键中断计时器

2024年10月01日8kerrycode

假设我想计算我能屏住呼吸的时间,我想用 Python 来做到这一点。我有简短的脚本:

start = time() 
try: 
    while True: pass 
except KeyboardInterrupt: 
    print(time() - start) 

这具有我想要的基本功能,但它有一个致命的缺点。屏住呼吸时间长了,脑子可能会有些模糊,可能找不到合适的位置马上按Ctrl+c,可能会丢失训练的重要数据。

空格键更容易命中。有没有一种简单的方法可以让循环在我按下时停止?

编辑:我在 OSX 上

请您参考如下方法:

您需要将控制台的键盘 (pty) 驱动程序置于原始模式。 在这个答案中有解释:What is the easiest way to detect key presses in python 3 on a linux machine?

大量引用该答案:

#! /usr/bin/env python3 
import sys 
import termios 
import time 
import tty 
 
 
def hold_breath(fin): 
    orig_setting = termios.tcgetattr(fin) 
    tty.setraw(fin) 
    start = time.time() 
    try: 
        ch = fin.read(1)[0] 
        assert ch == ' ' 
    finally: 
        print('You lasted %.03f seconds.\r' % (time.time() - start)) 
        termios.tcsetattr(fin, termios.TCSADRAIN, orig_setting) 
 
 
if __name__ == '__main__': 
    print('Hit space.') 
    hold_breath(sys.stdin) 

在 OS/X 和 Linux 上运行良好。如果您最终在程序恢复原始设置之前中断了程序,那么 $ stty sane 就是您的 friend 。