假设我想计算我能屏住呼吸多长时间,我想用 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 。
关于python - 用空格键中断计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45652980/