使用time.sleep()在同一行上打印

时间:2014-11-12 14:37:45

标签: python python-2.7

我正在尝试使用两者之间的计时器在同一行上打印两个字符串。这是代码:

import time

print "hello",
time.sleep(2)
print "world"

但似乎程序等待了两秒钟然后打印两个字符串。

2 个答案:

答案 0 :(得分:5)

问题是,默认情况下,控制台输出是缓冲的。 由于Python 3.3 print()支持关键字参数flushsee documentation):

print('hello', flush=True)

如果你使用python的先前版本f,你可以像这样强制刷新:

import sys
sys.stdout.flush()

答案 1 :(得分:2)

在python 2.7中,你可以使用 future 包中的print_function

from __future__ import print_function
from time import sleep

print("hello, ", end="")
sleep(2)
print("world!")

但就像你说的那样,等待2秒然后打印两个字符串。根据Gui Rava的回答,你可以刷新标准,这里有一个样本,可以让你朝着正确的方向:

import time
import sys

def _print(string):
    sys.stdout.write(string)
    sys.stdout.flush()

_print('hello ')
time.sleep(2)
_print('world')
相关问题