Python3 sleep() 问题
我正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为输出正在被缓冲。
您应该在每次写入后添加一个
sys.stdout.flush()
This is because the output is being buffered.
You should add a
sys.stdout.flush()
after each write听起来不同之处在于 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?