How can I flush the output of the print function?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Question
00:18 Accepted answer (Score 1817)
00:43 Answer 2 (Score 421)
01:07 Answer 3 (Score 340)
02:21 Answer 4 (Score 262)
07:52 Thank you
--
Full question
https://stackoverflow.com/questions/2307...
Accepted answer links:
[print]: https://docs.python.org/library/function...
[print]: https://docs.python.org/2/reference/simp...
[sys.stdout]: https://docs.python.org/2/library/sys.ht...
[file objects]: https://docs.python.org/2/library/stdtyp...
Answer 2 links:
[relevant documentation]: http://docs.python.org/using/cmdline.htm...
Answer 3 links:
[the documentation]: https://docs.python.org/3.3/library/func...
Answer 4 links:
[top of your module]: https://docs.python.org/2/reference/simp...
[see the ]: https://bitbucket.org/gutworth/six/src/3...
[docs]: https://docs.python.org/2/using/cmdline....
[docs]: https://docs.python.org/2/using/cmdline....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #printing #flush
#avk47
ACCEPTED ANSWER
Score 1914
In Python 3, print can take an optional flush argument:
print("Hello, World!", flush=True)
In Python 2, after calling print, do:
import sys
sys.stdout.flush()
By default, print prints to sys.stdout (see the documentation for more about file objects).
ANSWER 2
Score 446
You can change the flushing behavior using the -u command line flag, e.g. python -u script.py.
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'
Here is the relevant documentation.
ANSWER 3
Score 342
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.
ANSWER 4
Score 72
Also, as suggested in this blog post, one can reopen sys.stdout in unbuffered mode:
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Each stdout.write and print operation will be automatically flushed afterwards.