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?
Submitted by IncludeHelp, on June 14, 2020

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)

Python examples with 'flush' parameter in print()

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.

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.