简体   繁体   English

Python的print语句后跟sleep(…)函数提供了意外的输出

[英]Python's print statement followed by sleep(…) function gives unexpected output

Here's my Python 3 code: 这是我的Python 3代码:

from time import sleep
s='what is your name'
for x in s:
    print(x,end='')
    sleep(1)

What I expect is that, each letter will be printed one by one after a delay of one second. 我期望的是,每封信在延迟一秒钟后将一一打印。 But when I run this program, it takes a time of len(s) seconds and then prints the value of s . 但是,当我运行此程序时,它需要len(s)秒的时间,然后输出s的值。 Can anyone explain to me what is actually happening. 谁能向我解释实际情况。

Use flush argument to print function: 使用flush参数print功能:

print(x, end='', flush=True)

From docs : 文档

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed. 通常是否由文件决定是否对输出进行缓冲,但是如果flush关键字参数为true,则将强制刷新流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM