Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python printing inline with a sleep command

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?

like image 556
Algorithmatic Avatar asked Dec 04 '25 11:12

Algorithmatic


2 Answers

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.

like image 126
Prune Avatar answered Dec 07 '25 01:12

Prune


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...

like image 32
McGlothlin Avatar answered Dec 07 '25 01:12

McGlothlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!