如何使用 end=" 打印"立即在 Python 3 中? [英] How to print with end=" " immediately in Python 3?

查看:59
本文介绍了如何使用 end=" 打印"立即在 Python 3 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用没有换行符的打印语句并立即执行?

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

因为:

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

将在 5 秒后打印:

first second

但是我想写'first',等五秒钟,然后写'second'...

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

推荐答案

你需要刷新stdout:

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

stdout 是行缓冲的,这意味着每次打印换行符时缓冲区都会刷新到屏幕上.如果不打印换行符,则需要手动刷新.

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.

对于还没有使用 Python 3.3 或更高版本的任何人,flush 关键字参数是 3.3 中的新增功能.对于早期版本,您可以显式刷新 stdout:

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()

这篇关于如何使用 end=" 打印"立即在 Python 3 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆