How to flush a print in python

How to flush a print() in python:

flush is a parameter available in the print method. This parameter takes one boolean value. It is used to clean or clear the output stream.

flush is available only for Python-3. By default, it is False. We need to set it True to flush the stream.

How to flush in Python 2:

If you are using Python 2, there is another way to flush the output stream. You need to use sys module:

import sys

Syntax of print in Python 3:

In python 3, below is the syntax of print method:

print([arg1, arg2,....,], sep = '', end = '\n', filt = sys.stdout, flush = False)

The default value of flush is False. If we set it as True, it will flush the output stream.

Example of flush:

Let’s take a look at the below program:

from time import sleep

print('Hello ', end='')
print('World !!')

If you run it, it will wait for 5 seconds and then it will print the string Hello World !!.

But, if you enable flush, or mark flush as True, it will print Hello, wait for 5 seconds and print World !!.

from time import sleep

print('Hello ', end='', flush=True)
print('World !!')

You might also like: