closures缓冲

下面的缓冲区在哪里?我怎么把它关掉?

我正在写一个Python程序的标准输出,如下所示:

for line in sys.stdin: print line 

这里有一些缓冲:

 tail -f data.txt | grep -e APL | python -u Interpret.py 

我尝试了以下来摆脱可能的缓冲……没有运气:

  • 如上所述使用-u标志和python调用
  • 在每个sys.stdout.write()调用之后调用sys.stdout.flush()…所有这些创build一个缓冲的stream与Python等待的东西像一分钟打印出头几行。
  • 使用了以下修改的命令:

    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在您的环境中设置。