python - 读取多字符键盘笔划

标签 python python-3.x stdin termios

我有一个脚本可以在 python 中读取和处理键盘敲击。对于向 stdin 发送一个字节的标准键,这对我来说非常有效。我找不到合理的方法来读取产生多字节 ansi 转义码的击键。我需要做什么才能从 stdin 读取所有可用数据?

系统:OSX、Python 3.4

这是我的最小示例代码:

import sys
import termios
import select

# Save the terminal settings
fd = sys.stdin.fileno()
new_term = termios.tcgetattr(fd)
old_term = termios.tcgetattr(fd)

# New terminal setting unbuffered
new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)

while sys.stdin in select.select([sys.stdin], [], [], 10.0)[0]:
    char = sys.stdin.buffer.read(1)
    print('User input: {}'.format(char))

    if char == b'q':
        break

termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)


预期/期望的行为

当我启动脚本并按右箭头按钮时,我期望输出为:

b'\x1b'
b'['
b'C'

我实际得到的是:

b'\x1b'

如果我按下任何其他键,其他所有内容都会被读取。例如,如果我现在按“x”,我会得到:

b'['
b'C'
b'x'

如何通过初始按键获取所有三个字节?

最佳答案

当遇到 \x1b 时,请等待转义序列的其余部分。然后留一个超时,以防万一用户单独按下 esc。 Vim 就是这么做的,因为这是唯一的方法。

关于python - 读取多字符键盘笔划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38489809/

相关文章:

python - 当项目已存在以及使用 for 循环时将其添加到列表中

python - 在等待连接时如何关闭服务器套接字?

python - 页码python-docx

input - nodejs如何从标准输入读取击键

python - 将函数结果写入 stdin

python - Pandas DataFrame 将某些列合并到嵌套 JSON 中

python - 大收件箱 : Too many arguments for command 上的 imaplib.select

python - Flask返回404错误的随机模板

python - 同步 Python 脚本?

python - 如何为 Python 的 'input' 函数生成键盘输入?