【发布时间】:2016-07-04 04:07:21
【问题描述】:
我想以非阻塞的方式立即(不等待换行)捕获命令行上的“所有”键盘输入 方式。
This question 演示了如何使用select() 以非阻塞方式读取stdin。它是这样工作的:
while True:
if select.select([sys.stdin], [], [], 0)[0] == [sys.stdin]:
print(sys.stdin.read(1))
... do other stuff ...
不幸的是,您只有在按下 RETURN 后才能得到结果。
我的第一个猜测是stdin 只是行缓冲,所以在阅读了this question 之后我把我的代码变成了
ubuf_stdin = os.fdopen(sys.stdin.fileno(), 'rb', buffering=0)
while True:
if select.select([ubuf_stdin], [], [], 0)[0] == [ubuf_stdin]:
print(ubuf_stdin.read(1))
... do other stuff ...
这段代码工作得更好——缓冲区被完全读取而没有中断——但它仍在等待RETURN被按下。
我也试过detachstdin:
ubuf_stdin = os.fdopen(sys.stdin.detach().fileno(), 'rb', buffering=0)
我如何在按键后立即对键盘输入做出反应?
【问题讨论】:
-
question 的答案表明这是不可能的。
标签: python stdin nonblocking