如何在不阻塞整个应用程序的情况下读取单个按键?

问题描述 投票:0回答:1

因为我没有找到更好的方法来读取命令行上的按键,我目前使用的是 getch().

不幸的是,使用 getch() 像这样停止输出,在 stdout:

while True:
    handle_keystroke(getch())

按下按钮会触发 handle_keystroke()stdout 正在终端中打印--逐行打印每个按键。

提供的建议 此处 没有帮助。

我做错了什么?

另外:我不 需要 使用 getch(). 是否有更好的方法(如使用 select())?

更新。 (改变了标题)

只有当你使用多个线程时,这一切才会成为一个问题。因此,它看起来像 getch (这是一个非Python函数)不会释放GIL,所以所有其他线程都被暂停,所以不仅是 stdout 是受影响的。

python-3.x linux stdout flush
1个回答
0
投票

好了,找到了一个方法来使用 select 而不是 getch(). 诀窍是设置模式的 sys.stdoutcbreak:

import select
import tty
import termios
from contextlib import contextmanager

@contextmanager
def cbreak(stream):
    """Set fd mode to cbreak"""
    old_settings = termios.tcgetattr(stream)
    tty.setcbreak(stream.fileno())
    yield
    termios.tcsetattr(stream, termios.TCSADRAIN, old_settings)

with cbreak(sys.stdin):
    while True:
        select.select([sys.stdin], [], []) == ([sys.stdin], [], [])
        key = sys.stdin.read(1)
        handle_keystroke(key)
© www.soinside.com 2019 - 2024. All rights reserved.