Reputation: 1892
Why is the following code
from __future__ import print_function
from time import sleep
def print_inline():
print("Hello ", end='')
sleep(5)
print("World")
print_inline()
waits until the sleep is done to print Hello World
, shouldn't print Hello
then wait for 5 seconds and print World
in the same line?
Upvotes: 3
Views: 637
Reputation: 77837
No, it shouldn't. "Hello" sits in the output buffer until there's a reason to flush it to the output device. In this case, that "reason" is the end of the program. If you want The delayed effect, add
import sys
sys.stdout.flush()
just before your sleep statement.
See also a more complete discussion here.
Upvotes: 4
Reputation: 2099
If you set the first print
to:
print("Hello ", end='', flush=True)
this should print Hello
, then sleep for 5, then print World
.
Edit: this only works in Python 3, didn't see the Python 2.7 tag...
Upvotes: 4
Reputation: 593
import sys
sys.stdout.flush()
This is used to force the Python's print function to screen. See this answer also.
Upvotes: 0