下面的缓冲区在哪里……我该如何关闭它?
我正在像这样在 python 程序中写出到标准输出:
for line in sys.stdin:
print line
这里有一些缓冲:
tail -f data.txt | grep -e APL | python -u Interpret.py
我尝试了以下方法来摆脱可能的缓冲......没有运气:
- 如上在 python 调用中使用 -u 标志
- 在每次 sys.stdout.write() 调用后调用 sys.stdout.flush() ...所有这些都创建了一个缓冲流,python 等待大约一分钟来打印出前几行。
使用了以下修改后的命令:
stdbuf -o0 tail -f 数据.txt |标准缓冲区 -o0 -i0 grep -e APL | stdbuf -i0 -o0 python -u Interpret.py
为了衡量我的期望,我尝试了:
tail -f data.txt | grep -e APL
这会产生稳定的行流......它肯定不像 python 命令那样缓冲。
那么,如何关闭缓冲? ANSWER: 原来管道两端都有缓冲。
最佳答案
file.readlines()
和 for line in file
具有不受 -u
选项影响的内部缓冲(参见 -u option note ).使用
while True:
l=sys.stdin.readline()
sys.stdout.write(l)
相反。
顺便说一下,如果 sys.stdout
指向终端并且 sys.stderr
是无缓冲的(请参阅 stdio buffering),则默认情况下它是行缓冲的。
关于python - 关闭缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8416586/