gpt4 book ai didi

python - 标准输入非交互式时如何清除python中的标准输入缓冲区

转载 作者:行者123 更新时间:2023-11-28 18:39:08 26 4
gpt4 key购买 nike

如何在不阻塞的情况下从 python 中的标准输入缓冲区读取所有内容?我发现的堆栈溢出解决方案都不起作用,因为我的标准输入是非交互式的。

我试过:

tcflush

tcflush(sys.stdin, TCIOFLUSH) 不适用于非交互式标准输入。

选择

while select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
sys.stdin.read(1)

while len(select.select([sys.stdin.fileno()], [], [], 0.0)[0])>0:
os.read(sys.stdin.fileno(), 4096)

这是行不通的,因为 while 头部的条件总是 False

还有其他想法吗?

编辑

更准确地说:

我的代码应该

  • 如果输入缓冲区为空则什么都不做
  • 如果缓冲区有东西就清空

所以它应该永远阻塞。

最佳答案

您在 select() 调用中使用了零秒超时,这有效地使 select 进入了一次轮询操作,等待数据可用.

while len(select.select([sys.stdin.fileno()], [], [], 0.0)[0])>0:
^
|
This means don't wait

改为尝试:

while len(select.select([sys.stdin.fileno()], [], [], None)[0]) > 0:

关于python - 标准输入非交互式时如何清除python中的标准输入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com