Python3 sleep() 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4456581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:49:28  来源:igfitidea点击:

Python3 sleep() problem

pythonpython-3.xsleepflush

提问by roddds

I was writing a simple program on Python 3.1 and I stumbled upon this:

我在 Python 3.1 上写了一个简单的程序,我偶然发现了这个:

If I run this on the IDLE it works as intended - prints "Initializing."and then adds two dots, one after each second, and waits for input.

如果我在 IDLE 上运行它,它会按预期工作 - 打印"Initializing."然后添加两个点,每秒一个,然后等待输入。

from time import sleep

def initialize():
    print('Initializing.', end='')
    sleep(1)
    print(" .", end='')
    sleep(1)
    print(" .", end='')
    input()

initialize()

The problem is that when I double-click the .py to execute the file, it runs on python.exe instead of pythonw.exe, and strange things happen: it joins all the sleep()times i.e. makes me wait for 2 seconds, and then prints the whole string Initializing. . .at once. Why does this happen? Is there a way to avoid that happening in the terminal? It works fine if I use the IDLE in both windows and linux.

问题是当我双击 .py 执行文件时,它运行在 python.exe 而不是 pythonw.exe 上,奇怪的事情发生了:它一直加入,sleep()即让我等待 2 秒,然后打印Initializing. . .一次整个字符串。为什么会发生这种情况?有没有办法避免在终端中发生这种情况?如果我在 windows 和 linux 中都使用 IDLE,它工作正常。

采纳答案by John La Rooy

This is because the output is being buffered.

这是因为输出正在被缓冲。

You should add a sys.stdout.flush()after each write

您应该sys.stdout.flush()在每次写入后添加一个

回答by leoger

It sounds like the difference is that stdout is automatically being flushed in IDLE. For efficiency, programming languages often save up a bunch of print calls before writing to the screen, which is a slow process.

听起来区别在于标准输出会在空闲状态下自动刷新。为了提高效率,编程语言通常会在写入屏幕之前节省大量的打印调用,这是一个缓慢的过程。

Here's another question that has the answer you need: How to flush output of Python print?

这是另一个可以回答您需要的问题: 如何刷新 Python 打印的输出?