Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleeping and printing without newline? [duplicate]

Tags:

python

If I run this code:

for x in range(10):
    time.sleep(1)
    print("a")

It will do exactly what it should. But if I run this:

for x in range(10):
    time.sleep(1)
    print("a", end="")

It will wait the entire 10 seconds and then print the 10 a's.

How can I prevent this?

like image 842
tkbx Avatar asked Sep 18 '25 04:09

tkbx


1 Answers

Flush stdout after print.

import time
import sys

for x in range(10):
    time.sleep(1)
    print("a", end="")
    sys.stdout.flush()

Python 3.3 print function has optional flush parameter; You can write as follow in Python 3.3+.

import time

for x in range(10):
    time.sleep(1)
    print("a", end="", flush=True)
like image 76
falsetru Avatar answered Sep 19 '25 17:09

falsetru