2013-07-12 70 views
5

我有一个非常简单的应用:为什么我的python输出延迟到程序结束?

import sys 
from time import sleep 

for i in range(3): 
    sys.stdout.write('.') 
    sleep(1) 

print('Welcome!') 

我希望它打印出每秒(3次)点,之后它应该显示“欢迎光临!”。不幸的是,它只需等待三秒钟,然后一次打印出所有内容。我在运行普通Python 2.7的mac上,我不知道为什么这个代码的行为如此。有什么建议么?

+0

可能重复http://stackoverflow.com/questions/107705/ python-output-buffering) – Bruce

+0

查看[此问题](http://stackoverflow.com/questions/107705/python-output-buffering)了解更多详细信息(以及更高级的方式来执行您想要的操作)。 – abarnert

回答

8

这是因为sys.stdout被缓冲。使用flush

import sys 
from time import sleep 

for i in range(3): 
    sys.stdout.write('.') 
    sys.stdout.flush() 
    sleep(1) 

print('Welcome!') 
0

您应该使用printlogger

如果您想要您期望的行为,您需要使用sys.flush来强制输出。

1

stdout是一个缓冲流。缓冲区在到达换行符时隐式刷新。

如果要刷新缓冲区,而无需编写一个换行符,你必须通过调用sys.stdout.flush()

明确地这样做另一种选择是写stderr,这不是缓冲。

1

你可以调用python与-u使stdin,stdout和stderr完全无缓冲。这将使您不必手动刷新它们。

在Unix上,打电话给你的脚本一样python -u myscript.py

或者你可以把它的家当:#!/usr/bin/python -u

[Python的输出缓冲(的
相关问题