关闭缓冲

2024-04-23 18:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我在一个python程序中向stdout输出如下:

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 data.txt | stdbuf-o0-i0 grep-e APL | stdbuf-i0-o0 python-u Interpret.py

为了衡量我的期望,我试着:

tail -f data.txt | grep -e APL 

这会产生稳定的管线流。。。它肯定没有python命令那样缓冲。

那么,如何关闭缓冲? 答:原来管子的两端都有缓冲物。


Tags: py命令txtdatastdoutsyslinegrep
3条回答

问题在你的for循环中。它将等待EOF,然后继续。你可以用这样的代码来修复它。

while True:
    try:
        line = sys.stdin.readline()
    except KeyboardInterrupt:
        break 

    if not line:
        break

    print line,

试试这个。

我认为问题在于缓冲它的输出。当你用管道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终端。)

file.readlines()for line in file具有不受-u选项影响的内部缓冲(请参见-u option note)。使用

while True:
   l=sys.stdin.readline()
   sys.stdout.write(l)

相反。

顺便说一下,如果sys.stdout指向终端并且sys.stderr没有缓冲,则默认情况下sys.stdout是行缓冲的(请参见stdio buffering)。

相关问题 更多 >