Usage of sys.stdout.flush() method
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush()
forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO
How can I flush the output of the print function?
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).
Python sys.stdout.flush() doesn't seem to work
Remove the "\n" that creates a new line.
sys.stdout.write("\r{} out of {}...".format(count1, x))
What does print()'s `flush` do?
Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.
I do use it e.g. when I make a user prompt like Do you want to continue (Y/n):
, before getting the input.
This can be simulated (on Ubuntu 12.4 using Python 2.7):
from __future__ import print_function
import sys
from time import sleep
fp = sys.stdout
print('Do you want to continue (Y/n): ', end='')
# fp.flush()
sleep(5)
If you run this, you will see that the prompt string does not show up until the sleep ends and the program exits. If you uncomment the line with flush, you will see the prompt and then have to wait 5 seconds for the program to finish
Python - sys.stdout.flush() on 2 lines in python 2.7
to go to the upper line from the current one this has to be written on the stdout \x1b[1A
CURSOR_UP_ONE = '\x1b[1A'
to erase the contents of the line \x1b[2K
has to be written on stdout.
ERASE_LINE = '\x1b[2K'
this way you could go to the upper line and overwrite the data there.
data_on_first_line = CURSOR_UP_ONE + ERASE_LINE + "abc\n"
sys.stdout.write(data_on_first_line)
data_on_second_line = "def\r"
sys.stdout.write(data_on_second_line)
sys.stdout.flush()
for more details http://www.termsys.demon.co.uk/vtansi.htm#cursor
and https://stackoverflow.com/a/12586667
Related Topics
Check If a File Is Not Open Nor Being Used by Another Process
How to Remove Packages Installed with Python's Easy_Install
How to Read and Write Ini File with Python3
Check If Item Is in an Array/List
Interactive Input/Output Using Python
Pyqt Gui Size on High Resolution Screens
Python Memoising/Deferred Lookup Property Decorator
Execute a File with Arguments in Python Shell
Complexity of *In* Operator in Python
Matplotlib Fill Between Multiple Lines
How to Check the Versions of Python Modules
Python: Pandas Series - Why Use Loc
How to Add an Integer to Each Element in a List
How to Draw Intersecting Planes