How to print with end=“ ” immediately in Python 3?

醉酒当歌 提交于 2019-12-24 11:34:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!