Python3 sleep() 问题

发布于 2024-10-07 16:24:04 字数 557 浏览 0 评论 0原文

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

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

from time import sleep

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

initialize()

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

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

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

反目相谮 2024-10-14 16:24:04

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

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

This is because the output is being buffered.

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

动听の歌 2024-10-14 16:24:04

听起来不同之处在于 stdout 在 IDLE 中自动刷新。为了提高效率,编程语言通常会在写入屏幕之前保存大量打印调用,这是一个缓慢的过程。

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

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文