Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print function print lately on time consuming stuff

i am trying to understand, why start... is not print first. but got nothing...

from __future__ import print_function
# from time import sleep

def sleeping():
    # sleep(2)
    for i in range(60000000):  # or xrange(60000000)
        pass

print('start...', end='')
sleeping()
print('stop.')

same thing happen in this

from __future__ import print_function
from time import sleep

print('this will print lately')

sleep(2)

print('and this one')

i have tried this on both python 3 and 2. on python 2 it works fine.but causes problem on python 3.

EDIT:

different output on sublime text and terminal (may be configuration problem on sublime). on terminal, second one works well in both version and first one causes problem in both version.

like image 931
cwgt Avatar asked Nov 17 '25 11:11

cwgt


1 Answers

sys.stdout (which print prints to by default) is line-buffered when running interactively.

Since print('start...', end='') makes the line not end, the output isn't automatically flushed out.

To force the buffer to be flushed, you can specify flush=True when calling print.

In your case: print('start...', end='', flush=True)

Another option is to flush the stream manually by using sys.stdout.flush().

Further reading:

  • Documentation of print
  • Documentation of sys.stdout
like image 83
Sebastian Paaske Tørholm Avatar answered Nov 20 '25 01:11

Sebastian Paaske Tørholm