编程语言
首页 > 编程语言> > 为什么即使在刷新和使用-u时python也会继续缓冲stdout?

为什么即使在刷新和使用-u时python也会继续缓冲stdout?

作者:互联网

$cat script.py
import sys

for line in sys.stdin:
    sys.stdout.write(line)
    sys.stdout.flush()

$cat script.py - | python -u script.py

输出正确,但只有在按下Ctrl-D后才开始打印,而下面的内容立即开始打印:

$cat script.py - | cat

这让我觉得缓冲不是来自猫.

我设法让它工作:

for line in iter(sys.stdin.readline, ""):

正如这里所解释的:Streaming pipes in Python,但我不明白为什么前一个解决方案不能按预期工作.

解决方法:

Python手册页显示了您的问题的答案:

   -u     Force stdin, stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin, stdout and stderr in binary mode.  Note that
          there  is  internal  buffering  in  xreadlines(),  readlines()  and file-object iterators ("for line in sys.stdin") which is not influenced by this
          option.  To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.

那就是:文件对象迭代器的内部缓冲是责备(并且它不会随着-u而消失).

标签:python,pipe,stdout,buffering
来源: https://codeday.me/bug/20190902/1793548.html