Python3 sleep()问题 [英] Python3 sleep() problem

查看:132
本文介绍了Python3 sleep()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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()

问题是当我双击.py来执行文件时,它在python.exe而不是pythonw.exe上运行,并且发生了奇怪的事情:它连接了所有sleep()次,即让我等待2秒钟,然后立即打印整个字符串Initializing. . ..为什么会这样?有没有办法避免在终端中发生这种情况?如果我在Windows和Linux中都使用IDLE,则效果很好.

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.

推荐答案

这是因为正在缓冲输出.

This is because the output is being buffered.

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

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

这篇关于Python3 sleep()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆