下面的缓冲区在哪里?我怎么把它关掉?
我正在写一个Python程序的标准输出,如下所示:
for line in sys.stdin: print line
这里有一些缓冲:
tail -f data.txt | grep -e APL | python -u Interpret.py
我尝试了以下来摆脱可能的缓冲……没有运气:
使用了以下修改的命令:
stdbuf -o0 tail -f data.txt | stdbuf -o0 -i0 grep -e APL | stdbuf -i0 -o0 python -u Interpret.py
以我的期望为基准,我尝试了:
tail -f data.txt | grep -e APL
这产生了稳定的stream水线…它肯定不像python命令那样缓冲。
那么,如何closures缓冲? 解答:事实certificate,pipe道两端都有缓冲。
这个问题,我相信是grep
缓冲它的输出。 当你管tail -f | grep ... | some_other_prog
时候是这样做的 tail -f | grep ... | some_other_prog
tail -f | grep ... | some_other_prog
。 为了让grep
每行刷新一次,使用--line-buffered
选项:
% tail -f data.txt | grep -e APL --line-buffered | test.py APL APL APL
其中test.py
是:
import sys for line in sys.stdin: print(line)
(在linux上测试,gnome-terminal。)
file.readlines()
和for line in file
有内部缓冲,不受-u
选项的影响(请参阅-u选项说明 )。 使用
while True: l=sys.stdin.readline() sys.stdout.write(l)
代替。
顺便说一下,如果sys.stdout
指向终端而sys.stderr
是无缓冲的(参见stdio缓冲 ),则默认是行缓冲。
问题在于for循环。 在继续之前,它将等待EOF。 你可以用这样的代码修复它。
while True: try: line = sys.stdin.readline() except KeyboardInterrupt: break if not line: break print line,
试试这个。
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
并确保PYTHONUNBUFFERED
在您的环境中设置。