How to flush output of Python print?

How do I force Python's print function to output to the screen?

This is not a duplicate of Disable output buffering - the linked question is attempting unbuffered output, while this is more general. The top answers in that question are too powerful or involved for this one (they're not good answers for this), and this question can be found on Google by a relative newbie.


import sys
sys.stdout.flush()

Print by default prints to sys.stdout .

References:

  • http://docs.python.org/reference/simple_stmts.html#the-print-statement
  • http://docs.python.org/library/sys.html
  • http://docs.python.org/library/stdtypes.html#file-objects

  • Running python -h , I see a command line option:

    -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'

    Here is the relevant doc.


    Since Python 3.3, you can force the normal print() function to flush without the need to use sys.stdout.flush() ; just set the "flush" keyword argument to true. From the documentation:

    print(*objects, sep=' ', end='n', file=sys.stdout, flush=False)

    Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

    All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

    The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

    链接地址: http://www.djcxy.com/p/13516.html

    上一篇: 如何删除(chomp)Python中的尾随换行符?

    下一篇: 如何刷新Python打印输出?