flush parameter in Python with print() function

Python | flush parameter in print(): In this tutorial, we are going to learn about the flush parameter with print() function, how does it work with print() function? By IncludeHelp Last updated : December 17, 2023

The 'flush' parameter in printf() function

flush parameter is used to flush (clear) the internal buffer/stream (or we can say it is used to flush the output stream), it has two values "False" and "True".

"False" is the default value i.e. if we don't use the flush parameter – then flushing of the stream will be False. If we specify "True" – stream flushes.

Output to a print() function is buffered, flushing the print() makes sure that the output that is buffered goes to the destination.

Note: "flush" is available in Python 3.x or later versions.

Syntax

print(argument1, argument2, ..., flush = value)

Examples

Example 1

See, the below program carefully and understand the difference. print() function prints the text with a newline and when a newline is found output is done. Here, in the above program, we are using the end parameter to disable the newline character. The output will not display for 5 seconds. Once the program's execution is reached to the sleep() statement, the text will be printed.

from time import sleep

# output is not flushed here
print("Hello, world!", end='')
sleep(5)
print("Bye!!!")

Output

Hello, world!Bye!!!

Hopefully, you noticed something is wrong. Yes! "Hello, world!" and "Bye!!!" are printing together.

Example 2

To fix this issue, specify the flush parameter with the "True" value. If it is true, the stream will be flushed.

from time import sleep

# output is flushed here
print("Hello, world!", end='', flush= True)
sleep(5)
print("Bye!!!")

Output

Hello, world!Bye!!!

Now, when you run the program "Hello, world!" will be printed first and then after 5 seconds "Bye!!!" will be printed.

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.