无需按Enter即可读取任何按键

时间:2017-06-24 12:52:42

标签: python

我需要读取用户按下的键而不等待输入。 我想要读取字符和箭头键。 我使用的解决方案与this topic相同。

import sys,tty,termios
def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(3)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

while(1):
    k=getch()
if k=='\x1b[A':
    print "up"
elif k=='\x1b[B':
    print "down"
elif k=='\x1b[C':
    print "right"
elif k=='\x1b[D':
    print "left"

如果我想阅读箭头键,我使用ch = sys.stdin.read(3),如果我想阅读单个字符,我使用ch = sys.stdin.read(1),但我需要阅读两种类型的键。

脚本的其余部分是用Python 2.7编写的,可以在Linux系统上运行。

因为我不是系统管理员,所以请 不建议安装新包装。

0 个答案:

没有答案