为什么即使在刷新和使用-u时python仍保持对标准输出的缓冲? [英] Why does python keep buffering stdout even when flushing and using -u?

查看:94
本文介绍了为什么即使在刷新和使用-u时python仍保持对标准输出的缓冲?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ 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时它才开始打印,而以下内容立即开始打印:

The output is right but it only starts printing once I hit Ctrl-D whereas the following starts printing right away :

$ cat script.py - | cat

这使我认为缓冲不是来自cat.

which led me to think that the buffering does not come from cat.

我设法做到了:

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

如此处所述: Python中的流管道,但我不明白为什么以前的解决方案无法按预期工作.

as explained here : Streaming pipes in Python, but I don't understand why the former solution doesn't work as expected.

推荐答案

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

Python manpage reveals the answer to your question:

   -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不会消失).

That is: file-object iterators' internal buffering is to blame (and it doesn't go away with -u).

这篇关于为什么即使在刷新和使用-u时python仍保持对标准输出的缓冲?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆