Why is my python output delayed until the end of the program?

I have a very simple application:

import sys from time import sleep for i in range(3): sys.stdout.write('.') sleep(1) print('Welcome!') 

I expect it to print dots every second (3 times), after which it should display "Welcome!". Unfortunately, it just waits three seconds and then prints everything all at once. I am on a Mac that runs regular Python 2.7, and I don’t know why this code behaves this way. Any suggestions?

+6
source share
4 answers

This is because sys.stdout buffered. Use flush :

 import sys from time import sleep for i in range(3): sys.stdout.write('.') sys.stdout.flush() sleep(1) print('Welcome!') 
+9
source

stdout is a buffer stream. The buffer is flushed implicitly when it reaches the newline character.

If you want to flush the buffer without writing a newline, you must do this explicitly by calling sys.stdout.flush()

Another alternative is to write to stderr , which is not buffered.

+1
source

You can call python with -u so that stdin, stdout and stderr are not fully loaded. This eliminates the need to manually clean them.

On Unix, call the script as python -u myscript.py

Or you can put it in shebang: #!/usr/bin/python -u

+1
source

You must use print or logger .

If you need the behavior you expect, you need to use sys.flush to force the output.

0
source

Source: https://habr.com/ru/post/949292/


All Articles