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
sys.stdout.flush()
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='')
sleep(5)
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)
sleep(5)
print('World !!')
You might also like:
- Python program to get the current working directory
- How to execute a python code from a string
- Python program to check if a string holds binary content
- Python dictionary setdefault() method explanation with example
- Python remove the last inserted item from a dictionary using popitem()
- Python program to add separator between parameters while using print() method