【发布时间】:2014-07-05 02:40:43
【问题描述】:
我有一个循环可以完成一些工作并将大量信息打印到标准输出。一遍又一遍(这是一个循环......)我想做的是检测用户何时/如果用户按下一个键(它可以是箭头,输入或字母),并在发生这种情况时做一些工作.
这应该是一个非常简单的子任务,但我在过去的四个小时里尝试了不同的方法,但几乎一无所获。
这只需要在 Linux 中工作。
我能得到的最好的就是下面这样的东西。但这部分有效,仅在 0.05 秒内捕获密钥。
import sys,tty,termios
class _Getch:
def __call__(self, n=1):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(n)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def getch(timeout=0.2):
inkey = _Getch()
k = ''
start_sec = time()
while(time() - start_sec < timeout):
if k == '':
k = timeout_call(inkey, timeout_duration=timeout - (time() - start_sec))
if k == u'\x1b':
k += inkey(2)
if k == u'\x1b[A':
return "up"
if k == u'\x1b[B':
return "down"
if k == u'\x1b[C':
return "right"
if k == u'\x1b[D':
return "left"
elif k == "q":
return 'q'
elif k == "\n":
return 'enter'
else:
return None
while True:
do_some_work_that_lasts_about_0_2_seconds()
key = getch(0.05)
if key:
do_something_with_the(key)
【问题讨论】: