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

前端 未结 2 2032
后悔当初
后悔当初 2020-11-30 09:57

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

The documentation says it is to forcibly flush

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 10:29

    Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.

    I do use it e.g. when I make a user prompt like Do you want to continue (Y/n):, before getting the input.

    This can be simulated (on Ubuntu 12.4 using Python 2.7):

    from __future__ import print_function
    
    import sys
    from time import sleep
    
    fp = sys.stdout
    print('Do you want to continue (Y/n): ', end='')
    # fp.flush()
    sleep(5)
    

    If you run this, you will see that the prompt string does not show up until the sleep ends and the program exits. If you uncomment the line with flush, you will see the prompt and then have to wait 5 seconds for the program to finish

提交回复
热议问题