Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

python - What does print()'s `flush` do?

There is a boolean optional argument to the print() function flush which defaults to False.

The documentation says it is to forcibly flush the stream.

I don't understand the concept of flushing. What is flushing here? What is flushing of stream?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of things to understand here. One is the difference between buffered I/O and unbuffered I/O. The concept is fairly simple - for buffered I/O, there is an internal buffer which is kept. Only when that buffer is full (or some other event happens, such as it reaches a newline) is the output "flushed". With unbuffered I/O, whenever a call is made to output something, it will do this, 1 character at a time.

Most I/O functions fall into the buffered category, mainly for performance reasons: it's a lot faster to write chunks at a time (all I/O functions eventually get down to syscalls of some description, which are expensive.)

flush lets you manually choose when you want this internal buffer to be written - a call to flush will write any characters in the buffer. Generally, this isn't needed, because the stream will handle this itself. However, there may be situations when you want to make sure something is output before you continue - this is where you'd use a call to flush().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...