【发布时间】:2023-04-08 22:47:01
【问题描述】:
这可能是一个菜鸟问题,但我找不到解决方法! 我需要清除python中的stdin缓冲区。
想象一下我正在运行以下 bash 脚本:
i=0
for (( ; ; ))
do
echo "$i"
((i++))
done
像这样从命令行运行:./loop.sh | python myProg.py
在 myProg.py 我希望有如下内容:
count = 100
f = fileinput.input()
while True:
sleep(2)
# clear stdin somehow ...
# and read the most recent 100 lines
i = 0
while i < count:
myBuffer[i] = f.readline()
if len(myBuffer[i]) > 0:
i += 1
print myBuffer
我不认为我可以在它之前阅读所有行,因为它以高速率吐出它们并且如果睡眠(仅用于测试 atm)是几分钟,它似乎很愚蠢......有没有在python中设置标准输入缓冲区大小的方法?或者只是截断/清除它?顺便说一句,我使用 python 2 所以没有 bufsize 参数
我在这里看了How to avoid Python fileinput buffering
有什么 python 方法吗?但我也尝试取消缓冲:https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe
更新: unbuffer 或 stdbuf 没有运气......
【问题讨论】:
标签: python file-io buffer stdin