【问题标题】:Turn off buffering关闭缓冲
【发布时间】:2012-01-15 00:56:36
【问题描述】:

下面的缓冲区在哪里...以及如何关闭它?

我正在像这样的 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 data.txt | stdbuf -o0 -i0 grep -e APL | stdbuf -i0 -o0 python -u Interpret.py

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

tail -f data.txt | grep -e APL 

这会产生稳定的行流......它肯定不像 python 命令那样缓冲。

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

【问题讨论】:

  • 我希望它是重复的。那里提到的解决方案都不适用于我的情况。

标签: python linux bash buffering


【解决方案1】:

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),则默认情况下是行缓冲的。

【讨论】:

  • 将第一行替换为l=None; while l!='': 这样循环在输入结束时终止?
【解决方案2】:

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

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

    if not line:
        break

    print line,

试试这个。

【讨论】:

    【解决方案3】:

    我相信问题在于grep 缓冲其输出。当您使用管道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 上测试。)

    【讨论】:

    • 是的!这就是答案!虽然准确地说,我不得不使用 While True: line=sys.stdin.readline() ... 你的建议对我不起作用。所以,我认为是管道两端的缓冲使它变得困难。 ...谢谢。
    • 嗯,有趣!什么版本的 Python,你使用什么操作系统? (我的版本适用于 Python2.7+Ubuntu+gnome-terminal)。
    • 好点。使用 Python 3,您的方法有效。在 python 2.6 中,它不会。
    【解决方案4】:

    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 并确保在您的环境中设置了PYTHONUNBUFFERED

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多