Search code examples
pythonsleep

time.sleep function hiding text until KeyboardInterrupt


When I use sleep in while True it's showing nothing until I do keyboard interrupt.

Here's my code:

from colorama import Back
from time import sleep
while True:
    print(Back.RED +'Lol' ,sep=" " ,end=" ")
    sleep(0.2)

Output:

 |py
 |c:/.../colograma.py
 |

It's empty...

When I do Ctrl-C it shows this:

Lol Lol Lol Lol Lol Lol Lol Lol Lol Lol Lol Lol Lol Lol Lol Traceback 
 (most recent call last):
  File "c:/Users/blabl/Desktop/LukaOzbijan/colograma.py", line 5, in 
 <module>
        sleep(0.2)
        KeyboardInterrupt

Solution

  • Output is buffered, and nothing is actually written to standard output until the buffer fills up. Add flush=True to output text immediately.

    print(Back.RED + 'Lol', end=" ", flush=True)
    

    (sep isn't needed because you only have one string being written per call to print.)