Question

How can I use print statement without newline and execute this immediately?

Because this:

print("first", end=" ")
time.sleep(5)
print("second")

will print after 5 sec both:

first second

But I want to write 'first', wait for five seconds, and then write 'second'...

Was it helpful?

Solution

You need to flush stdout:

print("first", end=" ", flush=True)

stdout is line buffered, which means the buffer is flushed to your screen every time you print a newline. If you are not printing a newline, you need to flush manually.

For anyone not yet using Python 3.3 or newer, the flush keyword argument is new in 3.3. For earlier versions you can flush stdout explicitly:

import sys

print("first", end=" ")
sys.stdout.flush()

OTHER TIPS

You could do it as follows as well:

import sys, time

sys.stdout.write("First ")
time.sleep(5)
sys.stdout.flush()
sys.stdout.write("Second\n")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top