What does print () `flush` do?

There is a logical optional argument to the print() flush function, which is set to False by default.

The documentation says that it must force a stream to clear.

I do not understand the concept of flushing. What is washed off here? What is flow flushing?

+7
source share
2 answers

Typically, output to a file or console is buffered with text output, at least until you print a new line. A flash ensures that any output that is buffered is sent to its destination.

I use it, for example. when I make a user request, for example Do you want to continue (Y/n): before receiving the input.

This can be modeled (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 line is not displayed until the dream ends and the program exits. If you uncomment a line with a flash, you will see a prompt, and then wait 5 seconds for the program to finish

+7
source

There are a couple of things. One of them is the difference between buffered I / O and unbuffered I / O. The concept is quite simple - an internal buffer is stored for buffered I / O. Only when this buffer is full (or some other event occurs, for example, it reaches a new line), "discarded" is output. With unbuffered I / O, whenever a call is made to output something, it will do this one character at a time.

Most I / O functions fall into the buffering category, mainly for performance reasons: it is much faster to write chunks at a time (all I / O functions end up with some description system calls, which are expensive.)

flush allows you to manually select when you want this internal buffer to be written - a call to the flash writes any characters in the buffer. Typically, this is not required because the thread will handle this on its own. However, there may be situations when you want to make sure that something is displayed before continuing - here you should use the flush() call.

+9
source

All Articles