flush parameter is used to flush (clear) the internal buffer/stream (or we can say it is used to flush the output stream), it has two values "False" and "True".

flush参数用于刷新 (清除)内部缓冲区/流(或者可以说它用于刷新输出流 ),它具有两个值“ False”和“ True”。

"False" is the default value i.e. if we don't use the flush parameter – then flushing of the stream will be False. If we specify "True" – stream flushes.

默认值为“ False”,即,如果我们不使用flush参数 ,则流的刷新将为False。 如果我们指定“ True” –流刷新。

Output to a print() function is buffered, flushing the print() makes sure that the output that is buffered goes to the destination.

缓冲输出到print()函数的内容,刷新print()可以确保缓冲的输出到达目的地。

Note: "flush" is available in Python 3.x or later versions.

注意: “ flush”在Python 3.x或更高版本中可用。

Syntax:

句法:

print(argument1, argument2, ..., flush = value)

在print()中带有'flush'参数的Python示例 (Python examples with 'flush' parameter in print())

See, the below program carefully and understand the difference. print() function prints the text with a newline and when a newline is found output is done. Here, in the above program, we are using the end parameter to disable the newline character. The output will not display for 5 seconds. Once the program's execution is reached to the sleep() statement, the text will be printed.

请仔细看下面的程序,并了解它们之间的区别。 print()函数用换行符打印文本,找到换行符后即完成输出。 在这里,在上面的程序中,我们使用end参数禁用换行符。 输出将不会显示5秒钟 。 一旦程序的执行到达sleep()语句,将打印文本。

from time import sleep

# output is not flushed here
print("Hello, world!", end='')
sleep(5)
print("Bye!!!")

Output:

输出:

Hello, world!Bye!!!

Hopefully, you noticed something is wrong. Yes! "Hello, world!" and "Bye!!!" are printing together.

希望您注意到有问题。 是! “你好,世界!” 和“再见!!!” 正在一起打印

To fix this issue, specify the flush parameter with the "True" value. If it is true, the stream will be flushed.

要解决此问题,请使用“ True”值指定flush参数 。 如果为true,则将刷新流。

from time import sleep

# output is flushed here
print("Hello, world!", end='', flush= True)
sleep(5)
print("Bye!!!")

Output:

输出:

Hello, world!Bye!!!

Now, when you run the program "Hello, world!" will be printed first and then after 5 seconds "Bye!!!" will be printed.

现在,当您运行程序“ Hello,world!”时 将首先打印,然后在5秒钟后打印“再见!!” 将被打印

翻译自: https://www.includehelp.com/python/flush-parameter-in-python-with-print-function.aspx

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐