在Python中测量按键间隔时间
使用以下代码:
>>> import time
>>> start = time.time()
>>> end = time.time()
>>> end - start
可以测量“开始”和“结束”之间的时间。那么,如何测量特定按键之间的时间呢?具体来说,如果一个模块运行后,用户开始输入内容,Python 怎么能测量第一个按键和回车键之间的时间呢?比如,我运行这个脚本,它提示:“请输入你的名字,然后按回车:”。我输入“Nico”,然后按回车。那我怎么能测量从“N”到回车键之间的时间呢?这个时间应该以秒为单位,并且在按下回车后,脚本应该结束。
3 个回答
0
在Windows系统上,你可以使用 msvcrt.kbhit() 这个功能来判断是否有按键被按下。想要查看一个详细的例子,可以参考 http://effbot.org/librarybook/msvcrt.htm。
1
你可以用一个简单的方法来做到这一点:
from time import time
begin = time.time()
raw_input() #this is when you start typing
#this would be after you hit enter
end = time.time()
elapsed = end - begin
print elapsed
#it will tell you how long it took you to type your name
3
这个方法在某些系统上是有效的!
import termios, sys, time
def getch(inp=sys.stdin):
old = termios.tcgetattr(inp)
new = old[:]
new[-1] = old[-1][:]
new[3] &= ~(termios.ECHO | termios.ICANON)
new[-1][termios.VMIN] = 1
try:
termios.tcsetattr(inp, termios.TCSANOW, new)
return inp.read(1)
finally:
termios.tcsetattr(inp, termios.TCSANOW, old)
inputstr = ''
while '\n' not in inputstr:
c = getch()
if not inputstr: t = time.time()
inputstr += c
elapsed = time.time() - t
想了解其他系统上如何实现非阻塞的控制台输入,可以查看 这个回答。