print() 的 `flush` 有什么作用? [英] What does print()'s `flush` do?

查看:47
本文介绍了print() 的 `flush` 有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print() 函数 flush 有一个布尔可选参数,默认为 False.

There is a boolean optional argument to the print() function flush which defaults to False.

文档说是强制刷新流.

我不明白冲洗的概念.这里流什么?什么是流冲洗?

I don't understand the concept of flushing. What is flushing here? What is flushing of stream?

推荐答案

通常输出到文件或控制台被缓冲,至少在打印换行符之前输出文本.刷新确保缓冲的任何输出都到达目的地.

Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.

我确实使用它,例如当我在获取输入之前发出像 Do you want to continue (Y/n): 这样的用户提示时.

I do use it e.g. when I make a user prompt like Do you want to continue (Y/n):, before getting the input.

这可以模拟(在使用 Python 2.7 的 Ubuntu 12.4 上):

This can be simulated (on Ubuntu 12.4 using Python 2.7):

from __future__ import print_function

import sys
from time import sleep

fp = sys.stdout
print('Do you want to continue (Y/n): ', end='')
# fp.flush()
sleep(5)

如果你运行这个,你会看到提示字符串直到睡眠结束并且程序退出才出现.如果你用flush取消注释行,你会看到提示,然后必须等待5秒让程序完成

If you run this, you will see that the prompt string does not show up until the sleep ends and the program exits. If you uncomment the line with flush, you will see the prompt and then have to wait 5 seconds for the program to finish

这篇关于print() 的 `flush` 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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