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?
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With