【发布时间】:2018-06-30 12:08:06
【问题描述】:
这在 Python 中似乎很难..
我正在尝试使用修饰键 CTRL、ALT 和 SHIFT 读取击键和组合。
我使用的是 Python 2.7。 它只需要在 Linux 上工作,但没有 X。
目前,我只能使用 sys.stdin.read() 读取击键,但 stdin.read() 就像文件一样工作,不会返回修饰符..
def getch():
"""getch() -> key character
Read a single keypress from stdin and return the resulting character.
Nothing is echoed to the console. This call will block if a keypress
is not already available, but will not wait for Enter to be pressed.
If the pressed key was a modifier key, nothing will be detected; if
it were a special function key, it may return the first character of
of an escape sequence, leaving additional characters in the buffer.
"""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
函数返回击键组合的方式很灵活。首先想到的可能是返回一个包含组合的列表或字典。但主要问题是,如何检测它?!
【问题讨论】:
标签: python python-2.7 keyboard stdin