问题
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'...
回答1:
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()
回答2:
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")
来源:https://stackoverflow.com/questions/22502671/how-to-print-with-end-immediately-in-python-3